drpsrvu85668
2013-10-17 19:29 阅读 101
已采纳

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

    点赞 评论 复制链接分享

相关推荐