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
Release: 2024-12-07 17:04:11
Original
312 people have browsed it

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}
}
Copy after login

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

With this implementation, the output will be:

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

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)
Copy after login

Output:

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

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)
Copy after login

Output:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template