Contents

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:

  1. Imported packages are initialized first (recursively, each package initialized once).
  2. Package-level variables in the current package are evaluated in dependency order.
  3. All init functions in the current package run in the order the source files are presented to the compiler.
  4. 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/sql drivers or image format 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 init functions in the same package.
  • init cannot return an error; failures inside init can only panic, which makes testing and startup diagnostics harder.
  • Use init judiciously and prefer explicit dependency wiring from main.

References