我想知道为什么以下代码中没有警告或错误允许我覆盖全局变量。// You can edit this code!// Click here and start typing.package mainimport "fmt"type MyStruct struct { MyInt uint32}func (s *MyStruct) MyMethod() { fmt.Println(s.MyInt)}var theStruct MyStructfunc 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()}
1 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
变量可以隐藏父作用域中的其他变量。在您的示例中,范围层次结构如下所示:
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 world\n")); err != nil {
log.Fatal(err)
}
if true {
// We can even shadow with different types!
err := 3
log.Println(err)
}
}
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报
0/150
提交
取消