有人可以向我解释这种行为吗?我无法理解为什么会发生这种情况(仍在学习 Go)。我的具体问题在源代码中用QUESTION.谢谢,迈克尔package main// Define a simple type and functions on this type.type Foo struct{}var foo *Foofunc (f *Foo) function() { if f == nil { panic("Why is f nil?") }}// Create a wrapper struct containg method pointers to a global receiver variable.type Example struct { f func()}var bar = &Example{ // QUESTION: When is foo actually evaluated? It seems at definition of bar and then it's fixed? // QUESTION: And why is its value at runtime not used to determine the (now initialized) receiver target? f: foo.function,}// Initialize the global variable.func init() { foo = new(Foo)}// Call the function on foo, which should be initialized in init.func main() { bar.f()}
1 回答

蝴蝶不菲
TA贡献1810条经验 获得超4个赞
这是语言规范中的相关部分:
https://golang.org/ref/spec#Package_initialization
所有全局变量都是基于依赖分析初始化的。所以当它初始化时:
var bar = &Example{
f: foo.function
}
它需要foo被初始化。因为没有为 定义初始化器foo,所以它是 nil。一旦所有变量初始化完成,init()函数就会运行并设置foo为非零值。
如果您将声明更改为:
var foo = new(Foo)
有用。
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报
0/150
提交
取消