Trace package initialization and init
Trace package initialization and init
Before main runs, Go initializes imported packages before their importers. Within a package, package-level variables are initialized according to declaration dependencies, then init functions run. A package is initialized once even if multiple packages import it. init has no parameters or results and cannot be called by name.
Create the files shown below in a fresh directory, then run go run . there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples; modules are covered in detail next.
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import ( "example.test/lesson/config" "fmt")
func init() { fmt.Println("main init") }func main() { fmt.Println(config.Value()) }
--- config/config.go ---package config
import "fmt"
var n = load()
func load() int { fmt.Println("config variable"); return 3 }func init() { fmt.Println("config init"); n++ }func Value() int { return n }config variable is printed during variable initialization; config init follows. main init occurs only after config finishes. Keep init short; use explicit functions returning errors for operations that can fail or need configuration.
Expected output:
config variableconfig initmain init4Follow variable dependencies
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import "fmt"
var total = base + 2var base = 5
func init() { fmt.Println("init", total); base = 9 }func main() { fmt.Println(base, total) }Although total appears first, base is initialized first because total depends on it. The later change to base does not recalculate total. Avoid relying on source file ordering across files; use explicit dependencies or initialization functions.
Expected output:
init 79 7Try it locally
Declare package-level value=2. In init multiply value by 3. Print value from main. Use a fresh module with the same go.mod shown above; run go run .
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Packages and visibility 04: Trace package initialization and init
Check the lesson objective before moving on.
When does a package init function run relative to its variables?
How often is an imported package initialized in a program?