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.

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

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据