Member-only story

Go Tips & Common Mistakes

Beck Moulton
4 min readMay 11, 2024

--

Execution mechanism of init () function

In Go language, initfunctions 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 initfunctions 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 initfunction is executed before package A's initfunction.
  • If neither package A nor package B depends on each other, but they are both dependent on the main package, then their initfunctions 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 ...")
}

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet