Golang返回nil不返回nil [英] Golang returning nil does not return nil

查看:459
本文介绍了Golang返回nil不返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义错误类型来包装错误,以便更轻松地在Golang中进行调试。当有打印错误时它可以工作,但是现在引起了恐慌。

I created a custom error type to wrap errors around for easier debugging in Golang. It works when there are errors to print, but now it is causing a panic.

演示

type Error struct {
    ErrString string
}

func (e *Error) Error() string {
    return e.ErrString
}

func Wrap(err error, str string) *Error {
    if err == nil {
        return nil
    }
    e := &Error{
        ErrString: str + err.Error(),
    }
    return e
}

当我调用函数时,它不会返回错误,我仍然应该能够包装错误。

When I call a function an it doesn't return an error, I should still be able to wrap the error.

预期的行为是,如果错误为nil,则应忽略该错误,不幸的是相反。

The expected behavior is that if the error is nil, it should simply ignore it, unfortunately it does the opposite.

func foo() error {
    err := bar()
    return Wrap(err, "bar called")
}

func bar() error {
    return nil
}

func main() {
    err := foo()
    if err != nil {
        fmt.Printf("Found error %v\n",err)
        return
    }
    fmt.Println("No Errors")
}

我希望它能打印没有错误。相反,即使错误为nil,它也会打印发现的错误< nil>

I expect it to print No errors. Instead it prints Found error <nil> even though the error is nil.

推荐答案

if err != nil

正在将err变量与nil 错误进行比较,但实际上是nil *错误

Is comparing a the err variable to a nil error , but its actually a nil *Error

将代码更改为

err:=foo()
var  nilerror *Error = nil
if err != nilerror {
    fmt.Printf("Found error %v\n",err)
    return
}
fmt.Println("No Errors")

产生了预期的结果。

这篇关于Golang返回nil不返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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