包内的初始化顺序 [英] Init order within a package
本文介绍了包内的初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有文件:
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.
这篇关于包内的初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文