Home >Backend Development >Golang >When and How Does Go's `init()` Function Execute?
When Does the init() Function Run?
The init() function is a special function in Go that runs during package initialization. It is typically used to perform initialization tasks that cannot be handled by the package's main() function.
According to the Go documentation, the init() function is called after all the variable declarations in the package have evaluated their initializers. This means that all global variables and their initializers will have been processed before the init() function is executed.
The following example demonstrates this behavior:
var WhatIsThe = AnswerToLife() func AnswerToLife() int { // 1 return 42 } func init() { // 2 WhatIsThe = 0 } func main() { // 3 if WhatIsThe == 0 { fmt.Println("It's all a lie.") } }
In this example, the AnswerToLife() function (1) is guaranteed to run before the init() function (2) is called. The init() function is then guaranteed to run before the main() function (3) is called.
Note that the init() function is always called, regardless of whether or not there is a main() function. Therefore, if you import a package that has an init() function, it will be executed.
The above is the detailed content of When and How Does Go's `init()` Function Execute?. For more information, please follow other related articles on the PHP Chinese website!