Go中Error的定义和使用

280 阅读1分钟

在Go的内置类型文件中src\builtin\builtin.go,error被定义为一个接口,如下

// 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
}

使用errors.New来返回一个error对象(实现了Error()函数的对象)。我们看New函数,如下 ``

package errors

// New returns an error that formats as the given text.
// Each call to New returns a distinct error value even if the text is identical.
func New(text string) error {
	return &errorString{text}
}

New函数其实是返回了一个errorString结构的实例的引用。我们再看下errorString结构的定义

// errorString is a trivial implementation of error.
type errorString struct {
	s string
}

在errors package中定义了errorString结构的方法Error()

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

我们注意到errors的New方法返回的是一个内置的包含了一个字符串属性的结构体对象的指针,这样就可以是同样的字符串,但是是两个不同的error对象,因为地址不同。[Errors are values]