为什么在Golang中定义之前要使用引用符号?

huangapple go评论93阅读模式
英文:

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函数开始运行之前根据依赖关系的顺序进行评估。因此,在第一个代码片段中,defaultServeMuxDefaultServeMux之前被声明和初始化。

当你在函数中声明变量时,它们按照定义的顺序进行评估。因此,在第二个代码片段中,在声明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.

huangapple
  • 本文由 发表于 2021年10月25日 11:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69702647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定