11

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Derek
  • 11,980
  • 26
  • 103
  • 162
  • 1
    Related: [What does lexical file name order mean?](http://stackoverflow.com/questions/31650965/what-does-lexical-file-name-order-mean) – icza Sep 28 '15 at 18:49
  • 2
    Though the spec says the build system is "encouraged" to provide filenames in lexical order, it's not mandatory. If your files are in a single package, it seems fairly easy to enforce an absolute order to ensure consistent behavior. – JimB Sep 28 '15 at 18:57

1 Answers1

13

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.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • 13
    I'd say for that safe bet to be really safe, each file should provide a function named like `initA()`, `initB()` etc and one of those files should call them all in a well-defined sequence in its `init()`. As an added bonus, and an important one, that would provide a clear hint to the reader. – kostix Sep 28 '15 at 19:11
  • 1
    Or better, if you have initialization that is order dependant, make those dependencies explicit. E.g. if you have `var a = fn()` in one file and `var fn = func() int { return 42 }` in another then the `fn` will always be initialized first; https://play.golang.org/p/W6UdA_6gSa (in other words it may make sense to rename one of the `init` functions and call it from another where needed). – Dave C Sep 28 '15 at 20:35
  • It might be worth saying that the order of the `var` lines in https://play.golang.org/p/W6UdA_6gSa does matter if they were located within the `function main()` block –  May 02 '20 at 03:08