Global Error Variable Remains Nil After Initialization
Problem
When initializing an error variable globally, it remains nil in another function within the same package. This can prevent panic conditions from being triggered as expected.
package main import ( "os" "fmt" ) var loadErr error func main() { f, loadErr := os.Open("asdasd") if loadErr != nil { checkErr() } if f != nil { fmt.Println(f.Name()) } } // panic won't be called because loadErr is nil func checkErr() { if loadErr != nil { panic(loadErr) } }
Answer
The issue arises because the variable loadErr in the main function is a new, local variable. The global variable is never assigned a value. To rectify this, the variable assignment should be simplified:
func main() { _, loadErr = os.Open("asdasd")
By using =, the global variable loadErr will be initialized, and any subsequent errors will be propagated correctly.
Additional Considerations
If you want to hold the return value from os.Open, you need to predeclare the second variable:
var f *os.File f, loadErr = os.Open("asdasd")
In this case, := cannot be used as it would create a local variable and disregard the global one.
The above is the detailed content of Why Does My Globally Initialized Error Variable Remain Nil in Another Function?. For more information, please follow other related articles on the PHP Chinese website!