Go: Package initialization and program execution order

In a nutshell

Program execution

Program execution begins by initializing the main package and then calling the function main. When main returns, the program exits. It does not wait for other goroutines to complete.

Package initialization

Example: In this example (from the Go language specification)…

var (
        a = c + b
        b = f()
        c = f()
        d = 3
)

func f() int {
        d++
        return d
}

…the initialization order is d, b, c, a.

Init function

Variables may also be initialized using init functions:

func init() { … }

Multiple such functions may be defined. They cannot be called from inside a program.

It follows that there can be no cyclic dependencies.

Package initialization happens in a single goroutine, sequentially, one package at a time.

Warning

Lexical ordering according to file names is not part of the formal language specification:

To ensure reproducible initialization behavior, build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler.
The Go Programming Language Specification: Package initialization

Comments

Be the first to comment!