Go判断err为何不用if err判断呢?

我们在用Go中判断是否存在err,一般是:

if err != nil {
    fmt.Println(err)
}

但是为何不使用这样判断呢?

if err {
    fmt.Println(err)
}
阅读 3.2k
3 个回答

在 golang 里 err (一般为 error 类型)不能转换为 bool 类型。

  1. go语言中的error部分的源码如下(其实源码上的英文注释已经解答了楼主的疑问,go语言就是这么设计来判断错误的):

    // The error built-in interface type is the conventional interface for
    // representing an error condition, with the nil value representing no error.
    type error interface {
     Error() string
    }

    说明error是接口类型。

  2. Go语言中只有强制类型转换,没有隐式类型转换,布尔型无法参与数值运算,也无法与其他类型进行转换。

源码参考:https://github.com/golang/go/...

小知识.
Goland这样写就可以避免每次都写 err!=ni.
( 手动狗头
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题