有人可以向我解释这种行为吗?我无法理解为什么会发生这种情况(仍在学习 Go)。我的具体问题在源代码中用QUESTION.
谢谢,迈克尔
package main
// Define a simple type and functions on this type.
type Foo struct{}
var foo *Foo
func (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()
}
蝴蝶不菲
相关分类