Home > Backend Development > Golang > How to Print the Value, Not the Pointer, of Nested Structs in Go?

How to Print the Value, Not the Pointer, of Nested Structs in Go?

Patricia Arquette
Release: 2024-11-29 16:44:10
Original
266 people have browsed it

How to Print the Value, Not the Pointer, of Nested Structs in Go?

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:

  1. 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)
    }
    Copy after login
  2. 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)
    }
    Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template