| 导读 | 在 Golang 语言开发中,我们经常会使用结构体类型,如果我们使用的结构体类型的变量包含指针类型的字段,我们在记录日志的时候,指针类型的字段的值是指针地址,将会给我们 debug 代码造成不便 |
在Golang中有原生的 fmt 格式化工具去打印结构体,可以通过占位符%v、%+v、%#v去实现,这3种的区别如下所示:
type User struct {
Name string
Age int
}
func main() {
user := User{
Name: "张三",
Age: 95,
}
fmt.Printf("%v\n", user)
fmt.Printf("%+v\n", user)
fmt.Printf("%#v\n", user)
}
打印结果如下所示:
{张三 95}
{Name:张三 Age:95}
main.User{Name:"张三", Age:95}
其中的区别:
type Dog struct {
Name string
Age int
}
type User struct {
Name string
Age int
Dog *Dog
}
func main() {
dog := Dog{
Name: "旺财",
Age: 2,
}
user := User{
Name: "张三",
Age: 95,
Dog: &dog,
}
fmt.Println(user)
fmt.Printf("%v\n", user)
fmt.Printf("%+v\n", user)
fmt.Printf("%#v\n", user)
}{张三 95 0xc000004078}
{Name:张三 Age:95 Dog:0xc000004078}
main.User{Name:"张三", Age:95, Dog:(*main.Dog)(0xc000004078)}// Stringer is implemented by any value that has a String method,
// which defines the ``native'' format for that value.
// The String method is used to print values passed as an operand
// to any format that accepts a string or to an unformatted printer
// such as Print.
type Stringer interface {
String() string
}func (d *Dog) String() string {
return "{\"name" + "\": \"" + d.Name + "\"," + "\"" + "age\": \"" + strconv.Itoa(d.Age) + "\"}"
}
func (u *User) String() string {
return "{\"name" + "\": \"" + u.Name + "\", \"" + "age\": \"" + strconv.Itoa(u.Age) + "\", \"dog\": " + u.Dog.String() + "}"
}{张三 95 {"name": "旺财","age": "2"}}
{Name:张三 Age:95 Dog:{"name": "旺财","age": "2"}}
main.User{Name:"张三", Age:95, Dog:(*main.Dog)(0xc000004078)}// GoStringer is implemented by any value that has a GoString method,
// which defines the Go syntax for that value.
// The GoString method is used to print values passed as an operand
// to a %#v format.
type GoStringer interface {
GoString() string
}
The GoString method is used to print values passed as an operand to a %#v format. (GoString 方法用于打印作为操作数传递给 %#v 格式的值)func (d *Dog) GoString() string {
return "{\"name" + "\": \"" + d.Name + "\"," + "\"" + "age\": \"" + strconv.Itoa(d.Age) + "\"}"
}
func (u *User) GoString() string {
return "{\"name" + "\": \"" + u.Name + "\", \"" + "age\": \"" + strconv.Itoa(u.Age) + "\", \"dog\": " + u.Dog.String() + "}"
}{张三 95 {"name": "旺财","age": "2"}}
{Name:张三 Age:95 Dog:{"name": "旺财","age": "2"}}
main.User{Name:"张三", Age:95, Dog:{"name": "旺财","age": "2"}}func main() {
dog := Dog{
Name: "旺财",
Age: 2,
}
user := User{
Name: "张三",
Age: 95,
Dog: &dog,
}
byteUser, _ := json.Marshal(&user)
fmt.Println(string(byteUser))
}{"Name":"张三","Age":95,"Dog":{"Name":"旺财","Age":2}}