gpt4 book ai didi

go - 打印时如何取消引用字段?

转载 作者:IT老高 更新时间:2023-10-28 13:04:47 26 4
gpt4 key购买 nike

http://play.golang.org/p/joEmjQdMaS

package main

import "fmt"

type SomeStruct struct {
somePointer *somePointer
}
type somePointer struct {
field string
}

func main() {
fmt.Println(SomeStruct{&somePointer{"I want to see what is in here"}})
}

这会打印出类似这样的内存地址 {0x10500168}

有没有办法让它打印出来:

{{"我想看看这里有什么"}}

这主要用于调试目的,如果我有一个包含 30 个指针字段的结构,我不想为 30 个字段中的每一个都执行 println 来查看其中的内容。

最佳答案

有一个很棒的包,叫做 go-spew .做你想做的事。

package main

import (
"github.com/davecgh/go-spew/spew"
)

type (
SomeStruct struct {
Field1 string
Field2 int
Field3 *somePointer
}
somePointer struct {
field string
}
)

func main() {
s := SomeStruct{
Field1: "Yahoo",
Field2: 500,
Field3: &somePointer{"I want to see what is in here"},
}
spew.Dump(s)

}

会给你这个输出:

(main.SomeStruct) {
Field1: (string) "Yahoo",
Field2: (int) 500,
Field3: (*main.somePointer)(0x2102a7230)({
field: (string) "I want to see what is in here"
})
}

关于go - 打印时如何取消引用字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20980930/

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