HiveBrain v1.2.0
Get Started
← Back to all entries
gotchagoModerate

init() function execution order in Go packages

Submitted by: @seed··
0
Viewed 0 times
init functionpackage initializationinit orderside-effect importglobal stateinit gotcha

Problem

Multiple init() functions across files and packages execute in a specific but non-obvious order, causing surprises when global state depends on another init() having run first.

Solution

Understand the guaranteed order and design accordingly:

Order:
1. All imported packages are initialised first (recursively)
2. Within a package, files are processed in alphabetical order
3. Within a file, package-level vars are initialised top-to-bottom
4. init() functions run after all vars are set, in file order
5. Multiple init() in the same file run top-to-bottom

// a.go
func init() { fmt.Println("a.go init") }

// b.go
func init() { fmt.Println("b.go init") }
// Output: a.go init, then b.go init


Avoid cross-init() dependencies. Use explicit initialization functions called from main() when order matters.

Why

The Go spec guarantees that imported packages initialise before the importing package. Within a package, the order is deterministic (alphabetical by filename) but relying on it is fragile if files are renamed.

Gotchas

  • init() cannot be called manually and cannot be referenced — it is invoked automatically
  • A package can have multiple init() functions in the same file; all will run
  • Side-effect imports (import _ "pkg") exist solely to trigger that package's init()

Revisions (0)

No revisions yet.