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.

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
initfunctions, thenmain. - Package-level variables initialize in dependency order, not textual order, and can cross files.
- Multiple
initfunctions in one package run in the order the compiler presents the files, which for the standardgotool is lexical file order — not something to rely on for correctness. - An
initcannot return an error;panicorlog.Fatalinside it terminates the process beforemainwith the init stack in the output. initruns beforeflag.Parse, so it cannot read command-line flags.- Blank imports (
_ "pkg") exist to trigger another package'sinit;database/sqldrivers and image codecs are the canonical examples. - Prefer an explicit constructor returning
error, orsync.Once, when the work can fail or needs to be testable.
Basic syntax and type signatures
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"
}
}// 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:
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
| Stage | What runs | Can fail | Can be tested |
|---|---|---|---|
| Imported packages | their variables and init functions, recursively | only by panic | indirectly |
| Package variables | var x = f() in dependency order | only by panic | no |
init functions | every func init() in the package | only by panic | no |
main | program entry | yes | n/a |
TestMain | test binary entry, after all init | yes | yes |
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.
var a = b + 1 // depends on b
var b = 2 // initialized first, because a needs it
// a == 3Practical edge cases and deep dives
1. Multiple init functions and the order across files
// 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:
func init() { registerFormat("json", parseJSON) }
func init() { registerFormat("yaml", parseYAML) }
func init() { registerFormat("toml", parseTOML) }2. Blank imports and registration
// 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)
}// storage/s3/driver.go
package s3
import "example.com/storage"
func init() {
storage.Register("s3", func() storage.Driver { return &driver{} })
}// 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
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:
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:
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
var a = b + 1
var b = a + 1
// compile error: initialization cycle for a
// a refers to b
// b refers to aThe 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
// 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 symptom | Cause | Fix |
|---|---|---|
func init must have no arguments and no return values | wrong signature | use func init() and log or panic on failure |
undefined: init | calling init explicitly | move the logic into a named function |
initialization cycle for x | package variables depend on each other | break the cycle with a function |
import cycle not allowed | two packages import each other | extract shared types into a third package |
Flags empty in init | flag.Parse has not run | read flags in main and pass them |
| Configuration read twice | init reads env, main reads env again | one loader, called explicitly |
Process exits before main | log.Fatal/panic in init | return an error from a setup function |
| Driver registered in one binary, missing in another | the blank import lives in a different main | keep the import with the code that opens it |
| Tests need a database because of an import | init opens a connection | move I/O into an explicit constructor |
| Order differs between build tools | relying on lexical file order | combine 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.