When is the init() function in the go language executed?

Executed before the main function

The init() function is part of go initialization. The runtime initializes each imported package. The initialization is not in the import order from top to bottom, but in accordance with the resolved dependencies. Packages without dependencies are initialized first .

 

Each package first initializes package-scope constants and variables (constants take precedence over variables), and then executes the package's init() function . The same package, or even the same source file, can have multiple init() functions. The init() function has no input parameters and return value, and cannot be called by other functions. The execution order of multiple init() functions in the same package is not guaranteed

Execution sequence: import -> const -> var -> init() -> main() 

A file can have multiple init() functions

Guess you like

Origin blog.csdn.net/qq_48626761/article/details/131979512