douyangcheng4965 2014-04-21 07:50
浏览 18
已采纳

如何在if-else中初始化错误类型

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!

  • 写回答

2条回答 默认 最新

  • dswm97353 2014-04-21 08:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 如何修改别人网站内的数字,各位接单的私我
  • ¥15 poi怎么在指定位置之后生成多个表格
  • ¥15 nginx在location设置了client_max_body_size依旧报错413
  • ¥15 C#添加WCF服务引用客户端调用方法没有反应
  • ¥15 stm32f103c8t6与esp8266
  • ¥15 使用Hadoop的MapReduce program
  • ¥15 Python发生IndexError错误如何解决?
  • ¥15 如何用matlab搭建激光器
  • ¥15 51单片机两路互补SPWM输出全桥逆变
  • ¥15 outlook左边用户名下拉为啥打不开了