Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go init Function: Package Initialization Order, Imports, and Side Effects

What runs before main, the order across imports and files, why init cannot return an error, and the sync.Once replacement that can be tested.

~5 min readGo
#Go#Architecture#Runtime
3D illustration of a dependency tree running package init functions in topological order before main

An init function runs once, automatically, when its package is initialized, before any code in that package is called and before main. It takes no arguments, returns nothing, cannot be referenced, and cannot be skipped — importing a package guarantees every one of its init functions has completed. That combination makes it useful for registering implementations and computing package-level tables, and dangerous for anything that can fail, because an init has no way to report an error except a panic.

Quick Summary

  • func init() must have no parameters and no results, may appear multiple times in a file and in multiple files of a package, and is not callable.
  • Order: imported packages initialize first (in dependency order), then package-level variables in this package, then this package's init functions, then main.
  • Package-level variables initialize in dependency order, not textual order, and can cross files.
  • Multiple init functions in one package run in the order the compiler presents the files, which for the standard go tool is lexical file order — not something to rely on for correctness.
  • An init cannot return an error; panic or log.Fatal inside it terminates the process before main with the init stack in the output.
  • init runs before flag.Parse, so it cannot read command-line flags.
  • Blank imports (_ "pkg") exist to trigger another package's init; database/sql drivers and image codecs are the canonical examples.
  • Prefer an explicit constructor returning error, or sync.Once, when the work can fail or needs to be testable.

Basic syntax and type signatures

go
package config import "os" var env = os.Getenv("APP_ENV") // runs first: dependencies of later vars come first var debug = env == "development" func init() { if env == "" { env = "production" } }
go
// Registration through a blank import. import ( _ "github.com/lib/pq" // its init calls sql.Register("postgres", ...) ) db, err := sql.Open("postgres", dsn)

The rules the compiler enforces:

go
func init() {} // ok // func init(x int) {} // func init must have no arguments and no return values // func init() error {} // same // init() // cannot call init // f := init // undefined: init (init is not declared in any scope)

Initialization order

StageWhat runsCan failCan be tested
Imported packagestheir variables and init functions, recursivelyonly by panicindirectly
Package variablesvar x = f() in dependency orderonly by panicno
init functionsevery func init() in the packageonly by panicno
mainprogram entryyesn/a
TestMaintest binary entry, after all inityesyes

The nested ordering inside a package is more precise than the table: a variable whose initializer depends on another variable is initialized after it, regardless of which file or which line declares it. A cycle among initializers is a compile error.

go
var a = b + 1 // depends on b var b = 2 // initialized first, because a needs it // a == 3

Practical edge cases and deep dives

1. Multiple init functions and the order across files

go
// a_setup.go package app import "fmt" func init() { fmt.Println("init: a_setup") } // b_setup.go package app import "fmt" func init() { fmt.Println("init: b_setup (1)") } func init() { fmt.Println("init: b_setup (2)") }

The go tool passes files to the compiler in lexical order, so the output is a_setup, then both b_setup functions in declaration order — b_setup (1) before b_setup (2). The language specification leaves the order of files to the implementation, so a build system that sorts differently could reverse them. Code that depends on one file's init running before another's is therefore relying on a convention rather than a guarantee; the reliable way to order two pieces of setup is to put them in one function, or to make one call the other explicitly.

Multiple init functions in a single file are legal and run top to bottom, which is occasionally used to group registration by category:

go
func init() { registerFormat("json", parseJSON) } func init() { registerFormat("yaml", parseYAML) } func init() { registerFormat("toml", parseTOML) }

2. Blank imports and registration

go
// storage/registry.go package storage import "sync" type Driver interface { Open(dsn string) (Conn, error) } var ( mu sync.RWMutex drivers = map[string]func() Driver{} ) func Register(name string, ctor func() Driver) { mu.Lock() defer mu.Unlock() if _, dup := drivers[name]; dup { panic("storage: duplicate driver " + name) } drivers[name] = ctor } func Open(name, dsn string) (Conn, error) { mu.RLock() ctor, ok := drivers[name] mu.RUnlock() if !ok { return nil, fmt.Errorf("storage: unknown driver %q", name) } return ctor().Open(dsn) }
go
// storage/s3/driver.go package s3 import "example.com/storage" func init() { storage.Register("s3", func() storage.Driver { return &driver{} }) }
go
// main.go import ( _ "example.com/storage/s3" // its init registers the driver "example.com/storage" ) conn, err := storage.Open("s3", dsn)

The blank import is the whole point of the pattern: the importing file does not name anything from s3, it only wants the side effect of its init. The cost is that the dependency is invisible — remove the import and the driver disappears with a runtime error, and no compiler check connects the two. Registration functions should therefore reject duplicates loudly (as above) and tests should assert the registry contents.

3. init runs before flags, and cannot fail

go
package main import ( "flag" "log" "os" ) var configPath string func init() { configPath = flag.String("config", "", "path to config") // wrong: flag not parsed yet data, err := os.ReadFile(configPath) if err != nil { log.Fatalf("read config: %v", err) // exits before main } _ = data } func main() { flag.Parse() // configPath is the default "", not the user's value }

Two problems compound here. flag.String registers the flag and returns a pointer, so assigning its result to a string does not even compile — but the intent, reading a flag in init, is the deeper mistake: flag.Parse has not run, so every flag holds its default. Second, log.Fatalf in an init calls os.Exit, bypassing every deferred function in the program and printing a stack that points at package initialization rather than at main.

The correct shape is an explicit setup called from main:

go
func main() { flag.Parse() cfg, err := loadConfig(*configPath) if err != nil { log.Fatalf("config: %v", err) } if err := run(cfg); err != nil { log.Fatal(err) } }

A library that must initialize lazily and exactly once has sync.Once:

go
var ( once sync.Once client *http.Client initErr error ) func defaultClient() (*http.Client, error) { once.Do(func() { client, initErr = newClientFromEnv() }) return client, initErr }

sync.Once keeps the "exactly once" property while returning an error and while letting tests control when initialization happens. Go 1.21 added sync.OnceValue and sync.OnceValues for the same pattern without the hand-written closure.

4. Initialization cycles and ordering between packages

go
var a = b + 1 var b = a + 1 // compile error: initialization cycle for a // a refers to b // b refers to a

The cycle is detected statically because Go computes a dependency graph for package-level variables. The same graph decides cross-package order: if package db imports config, then config's variables and init functions complete before any of db's. A subtlety follows — db's variables may be initialized before main's, but nothing in db can assume main has run anything, so a package that needs application configuration must receive it through a function, not read a main variable.

Import cycles are a separate compile error (import cycle not allowed), and they usually appear when two packages each need a type from the other. The fix is a third package holding the shared types.

5. Tests see init too

go
// db_test.go package db import "testing" func TestMain(m *testing.M) { // runs after this package's init, before any test code := m.Run() os.Exit(code) }

The test binary initializes every imported package exactly as a normal binary does, so a init that connects to a database or reads the filesystem runs during go test as well — including in CI, where those resources may not exist. That is the strongest argument against side-effectful init in library code: the side effect becomes a requirement for anyone who imports the package, including a test that only wanted one pure function from it. An init that only fills in-memory tables (a lookup map, a format registry) has no such cost.

Common mistakes and compiler errors

Error or symptomCauseFix
func init must have no arguments and no return valueswrong signatureuse func init() and log or panic on failure
undefined: initcalling init explicitlymove the logic into a named function
initialization cycle for xpackage variables depend on each otherbreak the cycle with a function
import cycle not allowedtwo packages import each otherextract shared types into a third package
Flags empty in initflag.Parse has not runread flags in main and pass them
Configuration read twiceinit reads env, main reads env againone loader, called explicitly
Process exits before mainlog.Fatal/panic in initreturn an error from a setup function
Driver registered in one binary, missing in anotherthe blank import lives in a different mainkeep the import with the code that opens it
Tests need a database because of an importinit opens a connectionmove I/O into an explicit constructor
Order differs between build toolsrelying on lexical file ordercombine into one init, or order explicitly

The judgment is simple to state and easy to violate: init is for work that cannot fail and must happen for the package to be usable at all — building a lookup table, registering a codec, setting a package-level constant from a compile-time fact. Everything else belongs in a constructor that returns an error, called from main or from the test, where the failure has a caller to report to.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.