英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论