user2671513
user2671513

Reputation:

Golang, Go : implicitly calling interface function?

http://play.golang.org/p/xjs-jwMsr7

I have this function

 func (e *MyError) Error() string {
    return fmt.Sprintf("AT %v, %s", e.When, e.What)
 } 

But

as you see below, I never called it but how come it is called in the final output?

type MyError struct {
    When time.Time
    What string
}

func (e *MyError) Error() string {
    return fmt.Sprintf("AT %v, %s", e.When, e.What)
}

func run() error {
    return &MyError{
        time.Now(), "it didn't work",
    }
}

func main() {
    if err := run(); err != nil {
        fmt.Println(err)
    }
}

Upvotes: 1

Views: 400

Answers (1)

nemo
nemo

Reputation: 57757

fmt.Println and the other functions in pkg/fmt analyze the objects passed to it. If it is an error, the function calls .Error() on the passed object and prints the string returned by Error().

See the source for details. The code says:

switch v := p.field.(type) {
case error:
    // ...
    p.printField(v.Error(), verb, plus, false, depth)
    return
// ...
}

The type of the passed object is checked in a type switch statement and in case of the object implementing the error interface, v.Error() is used as value.

Upvotes: 1

Related Questions