猿问

为什么这种关于方法指针和全局变量初始化的行为在 Go 中是正确的?

有人可以向我解释这种行为吗?我无法理解为什么会发生这种情况(仍在学习 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()

}


狐的传说
浏览 112回答 1
1回答

蝴蝶不菲

这是语言规范中的相关部分:https://golang.org/ref/spec#Package_initialization所有全局变量都是基于依赖分析初始化的。所以当它初始化时:var bar = &Example{    f: foo.function}它需要foo被初始化。因为没有为 定义初始化器foo,所以它是 nil。一旦所有变量初始化完成,init()函数就会运行并设置foo为非零值。如果您将声明更改为:var foo = new(Foo)有用。
随时随地看视频慕课网APP

相关分类

Go
我要回答