Home > Backend Development > Golang > Why Does My Globally Initialized Error Variable Remain Nil in Another Function?

Why Does My Globally Initialized Error Variable Remain Nil in Another Function?

DDD
Release: 2024-12-12 13:28:10
Original
324 people have browsed it

Why Does My Globally Initialized Error Variable Remain Nil in Another Function?

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)
    }
}
Copy after login

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")
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template