I have files:
main/
a.go
b.go
c.go
a.go:
package main
import "fmt"
func init(){
fmt.Println("a")
}
func main(){}
b.go:
package main
import "fmt"
func init(){
fmt.Println("b")
}
c.go:
package main
import "fmt"
func init(){
fmt.Println("c")
}
In what order will the strings be outputted?
Package initialization section as the name suggest is executed when package is initialized. This happens when first procedure/function from the package is executed after session is established or after package is (re)compiled.
According to the Go language specification, init() functions declared across multiple files in a package are processed in alphabetical order of the file name. For example, the init() declaration in a.go file would be processed prior to the init() function declared in file b.go.
If a package has one or more init() functions they are automatically executed before the main package's main() function is called.
In the most basic terms, A package is nothing but a directory inside your Go workspace containing one or more Go source files, or other Go packages. Every Go source file belongs to a package.
The order that the respective filenames were passed to the Go compiler.
The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler" so it's a safe bet that go build
does exactly that, and the inits will run in A-B-C order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With