liveBook · Manning

Init function

As explained in 100 Go Mistakes and How to Avoid Them

An init function is a special Go function that runs automatically to perform package initialization before program execution begins.

An init function is a parameterless, resultless Go function that initializes package state automatically. Package variables and constants are evaluated first, followed by init functions and then main. section 2.3.1

Avoid the common mistake of treating init as an ordinary callable function:

  • Initialize imported packages before the importing package; a dependency such as redis runs its init before main's init. section 2.3.1
  • Allow multiple init functions in one package or source file, but do not rely on their order across files because renaming files can change it. section 2.3.1
  • Use a blank import such as _ "foo" when package initialization is needed for side effects without directly using its exported API. section 2.3.1
  • Do not call init directly; it is reserved for automatic package initialization and produces a compilation error when invoked. section 2.3.1

Replace connection setup with caller-controlled initialization

Opening a database and storing it globally inside init forces failures to panic, creates the connection before every test, and lets package code control application-wide state. A createClient function instead returns either the connection or an error, allowing callers to retry, fall back, or choose when setup occurs. section 2.3.2

package main
 
import "fmt"
 
var a = func() int {
    fmt.Println("var")        #1
    return 0
}()
 
func init() {
    fmt.Println("init")       #2
}
 
func main() {
    fmt.Println("main")       #3
}

Trace the observable order from package-level variable initialization through init and finally main. section 2.3.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains signatures, package dependencies, file ordering, blank imports, and testing and error-handling trade-offs, but not runtime internals.
Examples
Demonstrates variable-init output, dependent redis and main packages, multiple init functions, blank imports, database setup, and HTTP handler registration.
What it assumes
Assumes familiarity with Go packages, imports, functions, variables, and tests while defining init behavior from its signature onward.
What you can do after
Diagnose initialization-order and startup-design problems, then move failure-prone setup into caller-controlled functions.
How it connects
Connects package initialization with imports, side effects, global variables, error handling, and unit testing.

Also explained in

Compare how 2 books explain init function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.