初始化后全局错误变量恐慌?初始化全局错误变量时,它可能会在同一软件包中显示为函数时。 This discrepancy arises from a misunderstanding of variable scoping.
In your first example, you use := to initialize both f and loadErr within the main function:
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() } }
无意中创建阴影全局变量的本地变量,在分配值之前明确声明全局变量很重要。在第一个示例中,您可以通过移动其定义来将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