包内的初始化顺序
问题描述:
我有文件:
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?
答
将各个文件名传递到Go编译器的顺序.
The order that the respective filenames were passed to the Go compiler.
转到规范说:鼓励构建系统提供属于同一软件包的多个文件按照词汇表文件名顺序排列到编译器",因此可以确信 go build
会做到这一点,并且init将按ABC顺序运行.
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.