英文:
Why does the quote be used before definition in Golang
问题
我正在学习 Golang
的源代码,我找到了这段代码:
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
在定义之前使用了引用符号,我写了一个类似的示例代码,但是出现了错误:
func main(){
type ServeMux struct {
hosts string
}
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
fmt.Printf("print [%s]\n", DefaultServeMux.hosts)
}
我得到了 undefined: defaultServeMux
的错误。
我想知道这段代码是如何成功编译的?
英文:
I am studying Golang
source code, I found codes
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
the quote is used before definition, I wrote a sample code like this but got error:
func main(){
type ServeMux struct {
hosts string
}
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
fmt.Printf("print [%s]\n", DefaultServeMux.hosts)
}
I got undefined: defaultServeMux
I want to know how can the codes compile successfully?
答案1
得分: 3
第一段代码展示了两个包级别的变量声明。包级别的变量声明在main
函数开始运行之前根据依赖关系的顺序进行评估。因此,在第一个代码片段中,defaultServeMux
在DefaultServeMux
之前被声明和初始化。
当你在函数中声明变量时,它们按照定义的顺序进行评估。因此,在第二个代码片段中,在声明DefaultServeMux
时,defaultServeMux
还没有被定义。
英文:
The first piece of code shows two package level variable declarations. Package level variable declarations are evaluated before main
starts running based on the order imposed by dependencies. Because of this, in the first snippet, defaultServeMux
is declared and initialized before DefaultServeMux
.
When you declare variables in a function, they are evaluated in the order they are defined. Because of this, in the second code snippet, at the point where DefaultServeMux
is declared, defaultServeMux
is not yet defined.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论