In Go, the init() function is a special, built-in function that is called automatically before the main() function runs. It is used to perform package-level initialization or setup that needs to happen before your program starts executing its main logic.
init()Automatic execution
init() manually; Go runs it automatically during program startup.One or more per package
init() functions (even in different files).Purpose
main().No parameters and no return
func init() {
// initialization code
}
package main
import "fmt"
var globalVar int
func init() {
fmt.Println("Initializing globalVar")
globalVar = 42
}
func main() {
fmt.Println("Main starts")
fmt.Println("globalVar =", globalVar)
}
Output:
Initializing globalVar
Main starts
globalVar = 42
init() ran automatically before main(), setting up globalVar.✅ Summary
init() is a startup hook for a package.main() and is ideal for initialization tasks.