Home > Backend Development > Golang > How to Customize Go\'s Print Output for Structs with Pointers?

How to Customize Go\'s Print Output for Structs with Pointers?

Mary-Kate Olsen
Release: 2024-12-12 16:02:12
Original
853 people have browsed it

How to Customize Go's Print Output for Structs with Pointers?

Customizing the Print Output of Structs with Pointers

When printing structs with pointers in Go, using the default %v format specifier may not provide the desired result. This is because it prints the pointer address instead of the content of the referenced struct.

To address this, there are two primary approaches: define a custom String method for the struct type or manually format the output.

Defining a Custom String Method

The preferred method is to implement the Stringer interface for the involved struct types. This can be done by adding a String() string method to the struct. The format string passed to the printf function will call this method instead.

For example:

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.Printf("v ==== %v \n", a) // Prints "v ==== A{a:1, B:B{b:2}}"
}
Copy after login

Manual Formatting

In the absence of a String method, you can format the output manually using the format specifiers of the individual struct members.

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 ==== A{a:%d, B:B{b:%d}}\n", a.a, a.B.b)
}
Copy after login

The above is the detailed content of How to Customize Go\'s Print Output for Structs with Pointers?. 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