Printing Struct Values with Pointers in Go
In Go, when printing a struct value that contains pointers, the pointer address is typically printed instead of the actual value. This can be problematic when trying to inspect the contents of a nested struct.
How to Print the B Struct Value Instead of the Pointer
To solve this issue, you have two options:
Implement the Stringer Interface:
Implement the String() method for the A and B structs. This method returns a formatted string representation of the struct. In the implementation, print the desired values instead of the pointers.
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}} fmt.Println(a) }
Print Values Manually:
Access the actual values of the B struct manually and print them directly.
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("A{a:%d, B:{b:%d}}\n", a.a, a.B.b) }
The above is the detailed content of How to Print the Value, Not the Pointer, of Nested Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!