Home >Backend Development >Golang >Why Does My Global Error Variable Remain Nil After Initialization in Go?
Global Error Variable Remains Nil After Initialization: Uncovering the Discrepancy
Consider the following code:
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) } }
Perplexingly, this code does not panic, even though loadErr is nil. The same function checkErr() is defined to panic when loadErr is not nil. What is causing this discrepancy?
The Mystery Unveiled
The root of the issue lies in the subtle distinction between local and global variables. In the first code snippet, the line:
f, loadErr := os.Open("asdasd")
creates a new, local loadErr variable within the scope of the main function. This local variable is distinct from the global loadErr declared outside of any function. As a result, the global loadErr remains untouched and nil throughout the execution of the code.
Resolving the Discrepancy
To rectify the issue and ensure that the global loadErr is set, replace := with = in the line mentioned above:
func main() { _, = os.Open("asdasd")
This change assigns the value of os.Open() directly to the global loadErr, thereby correctly setting it to the desired value.
Additional Note
If you wish to retain the value of f as well, predeclare f outside the function scope:
var f *os.File func main() { f, = os.Open("asdasd")
Using := in this case would create a local f variable, eclipsing the global one.
The above is the detailed content of Why Does My Global Error Variable Remain Nil After Initialization in Go?. For more information, please follow other related articles on the PHP Chinese website!