"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Doesn't My Global Error Variable Panic After Initialization in Go?

Why Doesn't My Global Error Variable Panic After Initialization in Go?

Posted on 2025-03-23
Browse:181

Why Doesn't My Global Error Variable Panic After Initialization in Go?

Why Doesn't Global Error Variable Panic After Initialization?

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.

Scoping and Initialization

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.

Setting the Global Variable

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.

Avoiding Shadowing

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.

Latest tutorial More>

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