When initializing a global error variable, it may appear unchanged to functions within the same package. 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()) } }
This line creates a new local variable for both f and loadErr. It does not modify the global variables defined outside of the function. Thus, when you call checkErr(), loadErr is still nil because it has not been set anywhere within the scope of the main function.
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 if loadErr != nil { checkErr() } }
By using =, you are explicitly assigning the value of the local err variable to the global loadErr variable. This allows the function checkErr() to access the modified global variable and trigger the panic.
To prevent inadvertently creating local variables that shadow global variables, it is important to declare global variables explicitly before assigning a value. In the first example, you can declare loadErr as a global variable outside the main function by moving its definition:
var loadErr error func main() { _, loadErr = os.Open("asdasd") if loadErr != nil { checkErr() } if f != nil { fmt.Println(f.Name()) } }
This ensures that the global loadErr variable is accessible and updated throughout the program.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3