如何在if-else中初始化错误类型 [英] How to initialize error type in if-else

查看:175
本文介绍了如何在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)
}

见上面,在if-else块中将使用 err 。我想用一个变量来得到结果,但是我怎么在这里初始化 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!

推荐答案

您可以通过声明变量来创建一个零值错误(这将是零)。
$ b

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.

这篇关于如何在if-else中初始化错误类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆