Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init order within a package

Tags:

go

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?

like image 494
Derek Avatar asked Sep 28 '15 18:09

Derek


People also ask

What is package initialize?

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.

What is init function in Go?

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.

When init is called in Golang?

If a package has one or more init() functions they are automatically executed before the main package's main() function is called.

What are packages in Golang?

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.


1 Answers

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.

like image 141
hobbs Avatar answered Oct 14 '22 19:10

hobbs