Member-only story
Go Tips & Common Mistakes
4 min readMay 11, 2024
Execution mechanism of init () function
In Go language, init
functions are special functions used to initialize packages or modules. They are automatically called before the program starts executing any user-defined functions. The Go language runtime system guarantees that the init
functions of all packages will be called before the program starts executing the main function. However, the specific calling order depends on the dependency relationship between packages.
- If package A depends on package B (for example, package A imports package B), then package B’s
init
function is executed before package A'sinit
function. - If neither package A nor package B depends on each other, but they are both dependent on the main package, then their
init
functions will be executed in the internal order of the compiler, which is usually related to their order in the file system, but not strictly guaranteed.
Let’s do an experiment:
Main package
package mainimport (
"fmt"
"go-init/db"
)func init() {
fmt.Println("package main init() func ...")
}func main() {
db.LoadModel() //顺序调换还是限制性另一个文件的init函数
db.LoadConfig()
fmt.Println("package main main() func ...")
}
Db package config.go:
package dbimport "fmt"func init() {
fmt.Println("package db init() func ...")
}func LoadConfig() {
fmt.Println("package db LoadConfig() func ...")
}