亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

覆蓋全局變量

覆蓋全局變量

Go
largeQ 2023-07-26 17:40:56
我想知道為什么以下代碼中沒有警告或錯誤允許我覆蓋全局變量。// 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)

? ? }

}


查看完整回答
反對 回復 2023-07-26
  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號