The Go init Function
The init function in Go is a special function that is called when a program starts. It is used to initialize the program and set up any necessary state.
What is the init Function?
init is a special package-level function defined by the Go language specification (func init(), taking no arguments and returning no values—it is not part of the os package or any standard library). A package may declare multiple init functions; they cannot be called directly by user code and are invoked automatically by the Go runtime during package initialization.
When is the init Function Called?
Per the Go Language Specification, program initialization follows package dependency order:
- Imported packages are initialized first (recursively, each package initialized once).
- Package-level variables in the current package are evaluated in dependency order.
- All
initfunctions in the current package run in the order the source files are presented to the compiler. - Only after every imported package finishes initializing does
main.main()execute.
When to use init?
Reserve init for lightweight, side-effect-safe static registration or simple package state:
- Registering drivers or codecs: e.g.,
database/sqldrivers orimageformat decoders. - Initializing static lookup tables that cannot be expressed in a single variable initializer.
Avoid putting fallible I/O (opening network connections, reading config files, connecting to databases) inside init; call explicit initialization functions from main that return error.
How to Use the init Function
Declare func init() directly in the package:
package main
import (
"fmt"
)
func init() {
fmt.Println("Initializing...")
}
func main() {
fmt.Println("Hello, world!")
}Important points to remember
- Do not rely on implicit file ordering between multiple
initfunctions in the same package. initcannot return anerror; failures insideinitcan onlypanic, which makes testing and startup diagnostics harder.- Use
initjudiciously and prefer explicit dependency wiring frommain.