package main
import (
	"fmt"
)
type Student struct{
	StudentName *string
}
type Teacher struct {
	TeacherName *string
	Student1 Student
	Student2 *Student
}

func main() {    
	studentName := "zhangsan"
	teacherName := "teacher"
	student := Student{
		StudentName:&studentName,
	}	
	teacher := Teacher {
		TeacherName : &teacherName,
		Student1: student,
		Student2: &student,
	}
	fmt.Printf("%v\n",teacher)	
}
{0xc0000a0220 {0xc0000a0210} 0xc0000b6018}

查询到网上的方法是,为指针添加 String 方法,如

func (s *Student) String() string{
	return fmt.Sprintf("{[CustomStudent]name:%s}",*s.StudentName)
}
{0xc000096220 {0xc000096210} {[CustomStudent]name:zhangsan}}

改为为结构体本身添加 String 方法 ok

func (s Student) String() string{
	return fmt.Sprintf("{[CustomStudent]name:%s}",*s.StudentName)
}
{0xc000010260 {[CustomStudent]name:zhangsan} {[CustomStudent]name:zhangsan}}

但是很明显,要为每个结构体手动添加 String 方法还是比较繁琐且枯燥的。而且我也不想改项目组里以前的代码,虽然加个 String 方法没啥太大风险。

之前做 java 虽然也是每个类都有 string 方法,但好歹是可以自动生成的,golang 里面打印这种日志大家有什么好方法吗?