覆盖全局变量

  • 本文关键字:全局变量 覆盖 go
  • 更新时间 :
  • 英文 :


我想知道为什么以下代码中没有警告或错误,允许我覆盖全局变量。

// You can edit this code!
// Click here and start typing.
package main
import "fmt"
type MyStruct struct {
MyInt uint32
}
func (s *MyStruct) MyMethod() {
fmt.Println(s.MyInt)
}
var theStruct MyStruct
func main() {
// Override the above global variable
// I would expect some kind of warning or error here?
theStruct := MyStruct {
MyInt: 42,
}
// Outputs 42
theStruct.MyMethod()
// Outputs 0
UseMyStruct()
}
func UseMyStruct() {
theStruct.MyMethod()
}

允许变量隐藏父作用域中的其他变量。在您的示例中,范围层次结构如下所示:

global (scope)
├── theStruct (variable)
└── main (scope)
└── theStruct (variable)

像这样的阴影通常通过err来完成:

package main
import (
"io/ioutil"
"log"
)
func main() {
f, err := ioutil.TempFile("", "")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// This err shadows the one above, it is technically in its
// own scope within the "if".
if _, err := f.Write([]byte("hello worldn")); err != nil {
log.Fatal(err)
}
if true {
// We can even shadow with different types!
err := 3
log.Println(err)
}
}

这个例子部分来自"Go 中的范围和阴影"。

最新更新