Home >Backend Development >Golang >How to Print a Struct\'s Nested Pointer Value in Golang Without the Pointer Address?

How to Print a Struct\'s Nested Pointer Value in Golang Without the Pointer Address?

DDD
DDDOriginal
2024-12-07 17:04:11311browse

How to Print a Struct's Nested Pointer Value in Golang Without the Pointer Address?

How to Print Struct Value with Pointer in Golang

Consider the following code snippet:

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) // output: v ==== &{a:1 B:0xc42000e204}
}

Here, you want to print the value of B without its pointer representation. To achieve this, there are a few options:

1. Implementing the Stringer Interface:

The fmt.Printf() function calls the String() method if it exists for the type being printed. Implement the String() method for both A and B structures:

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, the output will be:

v ==== A{a:1, B:B{b:2}}

2. Customizing the Print Format:

You can directly format the output string to include only the desired fields:

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}}

3. Referencing Values in the Struct:

Since B is a field within A, you can directly reference its value:

fmt.Printf("v ==== A{a:%d, B:%v}", a.a, a.B)

Output:

v ==== A{a:1, B:&{b:2}}

The above is the detailed content of How to Print a Struct\'s Nested Pointer Value in Golang Without the Pointer Address?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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