golang Stringer接口

fmt 包中定义的 Stringer 是最普遍的接口之一。

type Stringer interface {
String() string
}
Stringer 是一个可以用字符串描述自己的类型。fmt 包(还有很多包)都通过此接口来打印值。

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


运行结果:

Arthur Dent (42 years) Zaphod Beeblebrox (9001 years)

发布了70 篇原创文章 · 获赞 1 · 访问量 1220

猜你喜欢

转载自blog.csdn.net/weixin_39658118/article/details/104395058