」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 為什麼在GO初始化後我的全局錯誤變量不恐慌?

為什麼在GO初始化後我的全局錯誤變量不恐慌?

發佈於2025-03-23
瀏覽:904

初始化後全局錯誤變量恐慌? Why Doesn't My Global Error Variable Panic After Initialization in Go?
初始化全局錯誤變量時,它可能會在同一軟件包中顯示為函數時。 This discrepancy arises from a misunderstanding of variable scoping.

Scoping and Initialization

In your first example, you use := to initialize both f and loadErr within the main function:

func main() { f,loaderr:= os.open(“ asdasd”) 如果loaderr! = nil { checkerr() } 如果f! = nil { fmt.println(f.name()) } }

此行為F和LOADERR創建一個新的本地變量。它不會修改在函數之外定義的全局變量。 Thus, when you call checkErr(), loadErr is still nil because it has not been set anywhere within the scope of the main function.

Setting the Global Variable
func main() {
    f, loadErr := os.Open("asdasd")
    if loadErr != nil {
        checkErr()
    }
    if f != nil {
        fmt.Println(f.Name())
    }
}
In your second example, you use = to set the value of loadErr to the error returned by os.Open():

func main() { _,err:= os.open(“ asdasd”) loaderr = err 如果loaderr! = nil { checkerr() } }

通過=,您將本地err變量的值分配給Global Loaderr變量。這允許函數checkerr()訪問修改後的全局變量並觸發恐慌。

避免陰影

無意中創建陰影全局變量的本地變量,在分配值之前明確聲明全局變量很重要。在第一個示例中,您可以通過移動其定義來將LOADERR聲明為主函數之外的全局變量:[&&&&&&&&&&&&&&&&&&var loaderr error func main(){ _,loaderr = os.open(“ asdasd”) 如果loaderr! = nil { checkerr() } 如果f! = nil { fmt.println(f.name()) } } [&& && &&&& && && &&華

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3