%v%+v%#v
func main() {
num := 1
str := "ted"
sleep := false
fmt.Printf("num: %v, str: %v, sleep: %v\n", num, str, sleep)
stu := student{
id: 0,
name: "ted",
}
var numInterface interface{}
numInterface=num
fmt.Printf("stu: %v, numInterface: %v\n", stu, numInterface)
fmt.Printf("stu: %+v, numInterface: %+v\n", stu, numInterface)
fmt.Printf("stu: %#v, numInterface: %#v\n", stu, numInterface)
}
上述代码的执行结果如下:
num: 1, str: ted, sleep: false
stu: {0 ted}, numInterface: 1
stu: {id:0 name:ted}, numInterface: 1
stu: main.student{id:0, name:"ted"}, numInterface: 1
%v%+v%#v
同理当结构体中存在指针成员时,打印的指针成员的值是指针本身的值,而不是指针指向的值,参考如下代码:
package main
import "fmt"
type student struct {
id int32
name *string
}
func main() {
name := "gxt"
stu := student{id: 1, name: &name}
fmt.Printf("stu: %v\n", stu)
fmt.Printf("stu: %+v\n", stu)
fmt.Printf("stu: %#v\n", stu)
}
输出结果:
stu: {1 0xc000010240}
stu: {id:1 name:0xc000010240}
stu: main.student{id:1, name:(*string)(0xc000010240)}
fmtStringers
// 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
}
因此只需要给上述代码中的student结构体实现该接口即可。参考代码如下:
package main
import "fmt"
type student struct {
id int32
name *string
}
func (s student) String() string {
return fmt.Sprintf("{id: %v, name: %v}", s.id, *s.name)
}
func main() {
name := "ted"
stu := student{id: 1, name: &name}
fmt.Printf("stu: %v\n", stu)
fmt.Printf("stu: %+v\n", stu)
fmt.Printf("stu: %#v\n", stu)
}
结果如下:
stu: {id: 1, name: ted}
stu: {id: 1, name: ted}
stu: main.student{id:1, name:(*string)(0xc000010240)}
%#v
进一步考虑如果结构体中嵌套了其他结构体对象指针,这种情况需要怎么处理呢?参考如下代码:
package main
import (
"encoding/json"
"fmt"
)
type studentP struct {
id int32
name *string
score *score
}
type score struct {
math *int
english int
}
func (s *studentP) String() string {
return fmt.Sprintf("{id: %v, name: %v, score: %v}", s.id, *s.name, s.score)
}
func (s *score) String() string {
return fmt.Sprintf("{math:%v, english:%v}", *s.math, s.english)
}
func main() {
name := "gxt"
math := 99
stu := &studentP{
id: 0,
name: &name,
score: &score{
math: &math,
english: 100,
},
}
fmt.Printf("std: %v\n",stu)
}
结果如下:
std: {id: 0, name: gxt, score: {math:99, english:100}}
%v%+v
注意:在实现String()方法时,需要注意receiver是对象还是指针,关系到打印嵌套式结构体对象时的传参。