Go's init function

·

1 min read

You can define several init functions in a package or in the same source file.

Go will only use one go routine to call those init function, it will not invoke the next one until the previous one has returned.

Go's ref doesn't explicitly tell us the order it chose to call init functions in different files, but from the experiment, it appears that:

  1. If in the same package, go will call init function in different files in alphabetical order. For example, if you have defined init func in account.go and db.go, it will call the init function first in account.go
  2. If in the same file, there are multiple init functions, they will be called sequentially:

Example:

package main

import "fmt"

func main() {
    fmt.Println("main")
}

func init() {
    fmt.Println("init 1")
}

func init() {
    fmt.Println("init 2")
}

func init() {
    fmt.Println("init 3")
}

Run it:

init 1
init 2
init 3
main

But since Go's spec doesn't define this behavior, your code's logic shouldn't rely on this.

Reference: