该接口经常用于输出 struct 的值 或者记录struct数据日志

一个普遍存在的接口是 fmt 包中定义的 Stringer接口

发现 http://tour.studygolang.com/methods/6 中的说法有错误.经过查找go 源码Stringer的定义存放在下面的目录中

go String接口方法

定义为go String接口方法

下面为 studygolang的截图

go String接口方法

 

String()string 的实现

 


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)
}
 
 

go语言开发交流qq群 857263711

保持进步
希望每个人都能找到自己喜欢的方式生活、工作。

 

 

相关文章:

  • 2021-07-10
  • 2022-12-23
  • 2022-01-13
  • 2022-02-17
  • 2021-06-25
  • 2021-11-20
  • 2022-01-22
猜你喜欢
  • 2021-08-07
  • 2022-12-23
  • 2021-04-28
  • 2021-10-03
  • 2022-12-23
  • 2021-11-12
  • 2021-12-19
相关资源
相似解决方案