When Does the init() Function Run?
The init() function is a special function in Go that is called before the main() function of the package. It is commonly used for initializing variables and other setup tasks. But what exactly does the following sentence from Effective Go mean:
"And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized."
This means that the init() function runs after all the global variables in the current package, as well as any imported packages, have been initialized with their default values. It's important to note that the order of initialization is based on the lexical order of the package files, rather than the order in which the imports are declared.
As an example:
var GlobalVar1 = 10 func init() { GlobalVar1 = 20 } func main() { // GlobalVar1 is 20 }
In this example, the init() function is called after GlobalVar1 has been initialized to 10, and it overrides the value of GlobalVar1 to 20 before the main() function is called.
It's worth mentioning that the init() function is always called, regardless of whether or not the package has a main() function. This means that if you import a package that has an init() function, it will be executed before the init() function of your own package.
Additionally, multiple init() functions can be defined within a single package, and they will be executed in the order they appear in the source file. This allows you to perform multiple initialization tasks in a specific order.
The above is the detailed content of When Exactly Does Go's `init()` Function Run?. For more information, please follow other related articles on the PHP Chinese website!