golang如何使用指针打印结构值 [英] golang how to print struct value with pointer
问题描述
package main
import "fmt"
type A struct {
a int32
B *B
}
type B struct {
b int32
}
func main() {
a := &A{
a: 1,
B: &B{
b: 2,
},
}
fmt.Printf("v ==== %+v \n", a)
}
//ret: v ==== &{a:1 B:0xc42000e204}
//??? how to print B's content but not pointer
推荐答案
基本上,您必须自己做.有两种方法可以做到这一点.要么只是打印您想要的东西,要么通过添加func String() string
为结构实现Stringer
接口,当您使用格式%v
时会调用该接口.您还可以使用结构形式的格式引用每个值.
Basically, you have to do it yourself. There are two ways to do this. Either just print the thing how you want, or implement the Stringer
interface for the struct by adding a func String() string
, which gets called when you use the format %v
. You could also reference each value in the format which is a struct.
实现Stringer
界面是始终获得所需内容的最可靠方法.而且您只需要对每个结构执行一次操作,而不必在打印时对每个格式字符串执行一次.
Implementing the Stringer
interface is the surest way to always get what you want. And you only have to do it once per struct, instead of per format string when you print.
https://play.golang.org/p/PKLcPFCqOe
package main
import "fmt"
type A struct {
a int32
B *B
}
type B struct{ b int32 }
func (aa *A) String() string {
return fmt.Sprintf("A{a:%d, B:%v}",aa.a,aa.B)
}
func (bb *B) String() string {
return fmt.Sprintf("B{b:%d}",bb.b)
}
func main() {
a := &A{a: 1, B: &B{b: 2}}
// using the Stringer interface
fmt.Printf("v ==== %v \n", a)
// or just print it yourself however you want.
fmt.Printf("v ==== A{a:%d, B:B{b:%d}}\n", a.a, a.B.b)
// or just reference the values in the struct that are structs themselves
// but this can get really deep
fmt.Printf("v ==== A{a:%d, B:%v}", a.a, a.B)
}
这篇关于golang如何使用指针打印结构值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!