gpt4 book ai didi

pointers - golang如何用指针打印结构值

转载 作者:IT王子 更新时间:2023-10-29 00:43:32 24 4
gpt4 key购买 nike

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


//ret: v ==== &{a:1 B:0xc42000e204}
//??? how to print B's content but not pointer

最佳答案

基本上,你必须自己做。有两种方法可以做到这一点。要么只是打印你想要的东西,要么通过添加 func String() string 为结构实现 Stringer 接口(interface),当你使用格式 时调用它>%v。您还可以引用结构格式中的每个值。

实现 Stringer 接口(interface)是始终获得所需内容的最可靠方法。打印时每个结构只需执行一次,而不是每个格式字符串。

https://play.golang.org/p/PKLcPFCqOe

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

// using the Stringer interface
fmt.Printf("v ==== %v \n", a)

// or just print it yourself however you want.
fmt.Printf("v ==== A{a:%d, B:B{b:%d}}\n", a.a, a.B.b)

// or just reference the values in the struct that are structs themselves
// but this can get really deep
fmt.Printf("v ==== A{a:%d, B:%v}", a.a, a.B)
}

关于pointers - golang如何用指针打印结构值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43259971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com