How to initialize error type in if-else

前端 未结 2 2008
南旧
南旧 2021-02-12 09:42

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 = fu         


        
相关标签:
2条回答
  • 2021-02-12 10:19

    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.

    0 讨论(0)
  • 2021-02-12 10:36

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

    err := *new(error)
    
    0 讨论(0)
提交回复
热议问题