drpsrvu85668 2013-10-17 19:29
浏览 118
已采纳

Golang,Go:隐式调用接口函数?

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)
    }
}
  • 写回答

1条回答 默认 最新

  • douguanci9158 2013-10-17 19:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?