ERROR接口

112 阅读1分钟

1.error是一个接口,实现他要满足有Error方法

type error interface { 
Error() string 
}

2.包里面提供了一个类型实现了接口,可以直接调用New方法返回一个error

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

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

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

3.New方法返回的是*errorString指针类型,所以两个New返回的实例判断是地址的判断,是不相等的,用指针实现接口的目的是不想让一些自定义的错误仅仅因为消息相同就和底层比如io.EOF这样重要的错误相等

fmt.Println(errors.New("EOF") == errors.New("EOF")) // "false"