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

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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料