如何避免Golang结构体嵌套格式化输出指针地址

本文探讨了Go语言中结构体嵌套时使用%+v格式化输出的问题,即指针地址的显示,并提供了解决方案:通过实现结构体的String()方法来完整展示所有字段值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

go结构体存在嵌套结构体时,使用%+v格式化输出时会出现打印指针地址的问题,如:

type Student struct{
	Name string
	Desp string
}

type Teacher struct{
	Student []*Student
	Name string
}

func main() {
	teacher := new(Teacher)
	teacher.Name = "teacher"

	student := new(Student)
	student.Name = "student"
	student.Desp = "this is student"

	student2 := new(Student)
	student2.Name = "student2"
	student2.Desp = "this is student2"

	teacher.Student = append(teacher.Student, student)
	teacher.Student = append(teacher.Student, student2)
	result := fmt.Sprintf("%+v",*teacher)
	fmt.Print(result)
}

//输出:
//{Student:[0xc420080020 0xc420080040] Name:teacher}

如果要实现%+v格式化输出所有的内容,可以通过实现对应结构体的String()方法,如:

type Student struct{
	Name string
	Desp string
}

type Teacher struct{
	Student []*Student
	Name string
}

func (s *Student) String() string {
	return "{Name:"+s.Name+" "+"Desp:"+s.Desp+"}"
}

func main() {
	teacher := new(Teacher)
	teacher.Name = "teacher"

	student := new(Student)
	student.Name = "student"
	student.Desp = "this is student"

	student2 := new(Student)
	student2.Name = "student2"
	student2.Desp = "this is student2"

	teacher.Student = append(teacher.Student, student)
	teacher.Student = append(teacher.Student, student2)
	result := fmt.Sprintf("%+v",*teacher)
	fmt.Print(result)
}

//输出:
//{Student:[{Name:student Desp:this is student} {Name:student2 Desp:this is student2}] Name:teacher}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只努力的微服务

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值