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.
The above is the detailed content of Why Doesn't My Global Error Variable Panic After Initialization in Go?. For more information, please follow other related articles on the PHP Chinese website!