Golang how to print structure value using pointer
1 answer
Basically, you have to do it yourself. There are two ways to do this. Either just print what you need, or implement an interface Stringer
for the structure by adding func String() string
which is called when the format is used %v
. You can also refer to each value in a format that is a structure.
Implementing an interface Stringer
is the surest way to always get what you want. And you need to do it once for each structure instead of the format string when printing. In the meantime, there is no need to know about it. β
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)
}
+2
source to share