为什么Go中的错误是可以消除的? [关闭]

[编辑:关闭问题,避免暴风雨。]

Go中的错误可能为零。以下编译

   var err error
   err = nil 
   err = errors.New("hello")

Yet errors are values, and value types are not nillable in Go.

Looking at error, it is an ordinary interface:

type error interface {
    Error() string
}

通过此结构实现:

type errorString struct {
    s string
}

这里没有指针。有一种采用指针接收器的方法,

func (e *errorString) Error() string {
    return e.s
}

Yet that doesn't explain why error behaves as a pointer rather than a value.

errors.New() does return a pointer,

func New(text string) error {
    return &errorString{text}
}

which makes my third code line above more puzzling -- we are assigning the result of New to a value variable.

这是如何运作的?

评论
  • 长大嫁你
    长大嫁你 回复

    我认为您可能会混淆一些概念。是的,“错误就是值”,因为它们不是可以抛出的异常,而是像其他任何返回值一样,它们是从函数返回的常规值。 Go质量的“错误就是价值”与价值vs参考语义无关。

    The built-in type error is an interface, and all interface values are nilable, so error is nilable.