在一个包内初始化顺序

huangapple go评论90阅读模式
英文:

Init order within a package

问题

这些字符串将按照以下顺序输出:

a
b
c

英文:

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?

答案1

得分: 13

相应的文件名传递给Go编译器的顺序。

Go规范中提到“构建系统鼓励以词法文件名顺序呈现属于同一包的多个文件给编译器”,所以可以肯定go build会按照这个顺序执行,并且初始化函数将按照A-B-C的顺序运行。

英文:

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.

huangapple
  • 本文由 发表于 2015年9月29日 02:30:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/32829538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定