In the package initialization part of the Go specification, what does "lexical file name order" mean?
To ensure reproducible initialization behavior, build systems are
encouraged to present multiple files belonging to the same package in
lexical file name order to a compiler.
From Wikipedia:
Lexical order is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters.
In practice this means files names are compared as strings, using the character codes to decide order. Order of character codes of the English alphabet follow the natural order of the letters, but the character code order is important if non-letters are also part of the file name (e.g. digits and other characters like '-'
).
This is just a convention to define an (arbitrary) order of source files if a package contains multiple source files, an order which remains the same if the package is recompiled (and of course files are not renamed).
The purpose is so that source files are always processed in the same order, and therefore the package init()
functions will also be executed in the same order, and you will observe the same behavior. Often the order of package init()
functions does not matter, but there may be cases when it does. By following this lexical file name order convention, you can rely on the (fixed) execution order of the init()
functions.