小编典典

打印时如何取消对字段的引用?

go

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}

有没有办法打印它:

{{"I want to see what is in here"}}

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


阅读 191

收藏
2020-07-02

共1个答案

小编典典

有一个很棒的软件包,称为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"
 })
}
2020-07-02