我想知道為什么以下代碼中沒有警告或錯誤允許我覆蓋全局變量。// 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 關注
- 154 瀏覽
添加回答
舉報
0/150
提交
取消