dousao1175 2015-12-11 17:57
浏览 64
已采纳

Golang:接口方法在哪里?

I don't understand at which point an Interface method is being called. I'm looking at the following example from the Go Tour:

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func (p Person) String() string {
    return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}

func main() {
    a := Person{"Arthur Dent", 42}
    z := Person{"Zaphod Beeblebrox", 9001}
    fmt.Println(a, z)
}

Problem:

I understand that the func (p Person) receives the String() method and that it returns the string I want to display. But the fmt.Println in the main() method has to call String() at some point, right?

I had a look at the source of fmt in godoc, but I still cannot figure it out!

Another example:

If I add my own interface, lets say Stringer2 with a method called String2() and then create a func (p Person) String2() {....}. How does String() get executed by fmt.Println, but String2() not?

  • 写回答

2条回答 默认 最新

  • duanqiao8925 2015-12-11 18:15
    关注

    The value is passed to Println as an interface{}, and is checked if it satisfies the fmt.Stringer interface via a "type assertion" often in the form of a "type switch".

    func IsStringer(i interface{}) {
        switch s := i.(type) {
        case fmt.Stringer:
            fmt.Println("Person a has a String() method")
            fmt.Println(s.String())
        default:
            fmt.Println("not a stringer")
        }
    
        // OR for a single type
    
        if s, ok := i.(fmt.Stringer); ok {
            fmt.Println("Person a has a String() method")
            fmt.Println(s.String())
        }
    }
    

    However, other methods may take precedence when printing from the fmt package. There are first checks for fmt.Formatter, fmt.GoStringer, error, and then finally fmt.Stringer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效