Package initialization
…
The declaration order of variables declared in multiple files is determined by the order in which the files are presented to the compiler: Variables declared in the first file are declared before any of the variables declared in the second file, and so on. 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.
This paragraph does not affect the validity of a program. That is to say, if we take the example from last week:
var x = a
var a = 3
but spread it across files, it will still compile just fine:
Given a.go
:
package foo
var x = a
and b.go
:
package foo
var a = 3
Both of the following will work:
go build a.go b.go
go build b.go a.go
What changes is the runtime declaration of the variables. We can see this in action with the following two source files:
a.go
:
package main
func main() {}
var a = func() {
println("a")
return 3
}()
b.go
:
package main
var b = func() {
println("b")
return 7
}()
Now run them with the files compiled in different order:
$ go run a.go b.go
a
b
$ go run b.go a.go
b
a
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)