go String接口方法

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

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

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

定义为

下面为 studygolang的截图

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

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

 
原文地址:https://www.cnblogs.com/songhuan999999/p/11194291.html