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 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题