The error Interface

error interface has a single method that returns an error message:

type error interface { Error() string }

The simplest way to create an error is by calling errors.New, which returns a new error for a given error message. The entire errors package is only four lines long:

package errors func New(text string) error { return &errorString{text} } type errorString struct { text string } func (e *errorString) Error() string { return e.text }

The underlying type of errorString is a struct, not a string , to protect its representation from inadvertent (or premeditated) updates. And the reason that the pointer type *errorString, not errorString alone, satisfies the error interface is so that every call to New allocates a distinct error instance that is equal to no other.

We would not want a distinguished error such as io.EOF to compare equal to one that merely happened to have the same message.

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

Calls to errors.New are relatively infrequent because there’s a convenient wrapper function, fmt.Errorf, that does string formatting too.

package fmt import "errors" func Sprintf(format string, args ...interface{}) (s string) {

} func Errorf(format string, args ...interface{}) error { return errors.New(Sprintf(format, args...)) }

Next example: Type Assertions