Go supports the init function for performing initialization code before the main() starts. When running a Go program, the compiler automatically calls all init functions declared in each package after initializing the package variables.
Background: the need for one-time preparation of the package state before its usage.
Issue: the order of init initialization often leads to implicit errors: it is difficult to control when exactly a specific init function will be triggered, especially with multiple dependencies between packages.
Solution:
Code example:
package example import "fmt" var Cfg string = "default" func init() { fmt.Println("example init") Cfg = "configured" }
Key features:
Can you define more than one init function in a single file?
Yes, multiple init functions are allowed — they will be called in the order of their declaration.
What happens if a package is imported only indirectly (via _ "package")?
Only the init functions and the initialization of this package's variables will be executed.
Can init functions return a value or an error?
No. The signature of init is immutable: func init(), with no parameters and no return values.
A large project relied on complex init functions that initialized global states with dependencies between packages, causing floating runtime errors.
Pros:
Cons:
Init is used only for basic or test-specific tasks, with everything else moved to explicit functions called from main(). The order of execution is clear, and testing is simple.
Pros:
Cons: