”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 为什么在GO初始化后我的全局错误变量不恐慌?

为什么在GO初始化后我的全局错误变量不恐慌?

发布于2025-03-23
浏览:434

初始化后全局错误变量恐慌?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