How to initialize error type in if-else

2020-06-07 07:20发布

问题:

In the code snippet below, how do I 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, err will be used in the if-else blocks. I want to use one variable to get the result, but how do I initialize err here. Thanks!

回答1:

You can create a zero-valued error (which will be nil) by declaring the variable.

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

It's a common idiom, and you'll see it in plenty of code.



回答2:

This one looks a little hacky, but is valid too:

err := *new(error)


标签: go