1 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
變量可以隱藏父作用域中的其他變量。在您的示例中,范圍層次結(jié)構(gòu)如下所示:
global (scope)
├── theStruct (variable)
└── main (scope)
? ? └── theStruct (variable)
像這樣的陰影通常是通過(guò)以下方式完成的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 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)