Home >Backend Development >Golang >How to Print Nested Struct Values in Golang Without Memory Addresses?
When working with nested structs, it can be challenging to print their values without displaying their memory addresses. Let's look at this example:
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) }
When executing this code, you will see that the output contains the memory address of the nested struct B:
v ==== &{a:1 B:0xc42000e204}
To retrieve the actual value of B, you can adopt one of these approaches:
Implementing the Stringer interface for the nested struct allows you to define how its string representation will be formatted when printed. Here's how you can do it:
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) }
With this implementation, you can now use the %v format specifier to print a custom string representation of the struct:
fmt.Printf("v ==== %v \n", a) // Output: v ==== A{a:1, B:B{b:2}}
Alternatively, you can manually print the values without relying on the Stringer interface. This approach gives you more control over the output format:
fmt.Printf("v ==== A{a:%d, B:B{b:%d}}\n", a.a, a.B.b) // Output: v ==== A{a:1, B:B{b:2}}
If you want to avoid printing the struct reference, you can explicitly reference its values:
fmt.Printf("v ==== A{a:%d, B:%v}", a.a, a.B) // Output: v ==== A{a:1, B:&{b:2}}
However, this approach can become complex when dealing with deeply nested structs.
In summary, you can print nested struct values without pointers by implementing the Stringer interface, printing values manually, or referencing struct values directly. Choose the approach that best suits your specific needs.
The above is the detailed content of How to Print Nested Struct Values in Golang Without Memory Addresses?. For more information, please follow other related articles on the PHP Chinese website!