【golang】golang使用 String() 方法自定义类型的输出

对于结构体,有时候我们需要打印它的信息,但是打印出来是这样的:

type Family struct {
	Father  string
	Mather  string
	Brother string
}

func main() {
	f := Family{"fa", "ma", "bro"}

	fmt.Println(f)
}

输出:
{fa ma bro}

并不是很直观,golang允许你通过实现 String() 接口来自定义输出。

type Family struct {
	Father  string
	Mather  string
	Brother string
}

func main() {
	f := Family{"fa", "ma", "bro"}

	fmt.Println(f)
}

func (f Family) String() string {
	return "Father: " + f.Father + "\nMather: " + f.Mather + "\nBrother: " + f.Brother
}

输出:
Father: fa
Mather: ma
Brother: bro

或者使用引用的方式

type Family struct {
	Father  string
	Mather  string
	Brother string
}

func main() {
	f := &Family{"fa", "ma", "bro"}

	fmt.Println(f)
}

func (f *Family) String() string {
	return "Father: " + f.Father + "\nMather: " + f.Mather + "\nBrother: " + f.Brother
}

如果类型定义了 String() 方法,类似于 fmt.Printf() 中格式化描述符 %v 产生的输出。还有 fmt.Print() 和 fmt.Println() 也会自动使用 String() 方法。

不要在 String() 方法里面调用涉及 String() 方法的方法,它会导致意料之外的错误,比如无限递归调用。
类似于这样:

func (t TT) String() string {
    return fmt.Sprintf("%v", t.String())
}
修改
func (t TT) String() string {
    return fmt.Sprintf("%v", t)
}

也很好理解,因为 fmt.Sprintf 又会去再次调用 String(),从而形成无限递归。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惠菁

跪求一键三联

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值