How to initialize error type in if-else

In the code snippet below, how to initialize an error variable?

err := nil                // can not compile, show "use of untyped nil"
if xxx {
    err = funcA()
} else {
    err = funcB()
}
if err != nil {
    panic(err)
}

As you can see above, it errwill be used in if-else blocks. I want to use one variable to get the result, but how do I initialize errhere. Thank you

+4
source share
1 answer

You can create a null error (which will be zero) by declaring a variable.

var err error
if xxx {
    err = funcA()
} else {
    err = funcB()
}

This is a common idiom, and you will see it in a lot of code.

+9
source

Source: https://habr.com/ru/post/1537337/


All Articles