The init() Function
In this page:
Defining init()
A function named init with no parameters or return values runs automatically as soon as its package is initialized, before the program's main() function begins -- you never call it explicitly yourself.
Example: Defining init()
package main
import "fmt"
func init() {
fmt.Println("init runs first")
}
func main() {
fmt.Println("main runs second")
}
Login to try C/C++/Java/PHP code in the editor
Multiple init() Functions
A single package can contain multiple init() functions, even several within one file, and Go runs all of them in the order they appear (across files, in filename order) before main starts.
Example: Multiple init() Functions
package main
import "fmt"
func init() {
fmt.Println("first init")
}
func init() {
fmt.Println("second init")
}
func main() {
fmt.Println("main")
}
Login to try C/C++/Java/PHP code in the editor
Common Uses for init()
init() is typically used for one-time setup that must happen before any other code runs, like validating required configuration or registering something with a shared registry, since it's guaranteed to run before main.
Note: Prefer an explicit setup function over init() when the initialization order or parameters genuinely matter to callers.
Example: Common Uses for init()
package main
import "fmt"
var validConfig bool
func init() {
validConfig = true // pretend this checked real configuration
}
func main() {
fmt.Println("config valid:", validConfig)
}
Login to try C/C++/Java/PHP code in the editor
- Relying on a specific execution order across multiple init() functions in different files without understanding Go's file-name-based ordering rules within a package.
- Using init() for complex application logic that would be clearer as an explicit, callable setup function.
- Forgetting a package can have multiple init() functions (even multiple per file), all of which run automatically.
- func init() runs automatically when a package is loaded, before main() starts.
- A package can define multiple init() functions, even several in the same file.
- init() takes no arguments and returns no values -- it can't be called explicitly.
- It's commonly used for one-time setup like registering drivers or validating configuration.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: