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

问题描述 投票:0回答:4

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 来查看其中的内容。

go printf
4个回答
23
投票

有一个很棒的软件包叫做 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"
 })
}

2
投票
package main

import (
    "fmt"
)


type SomeTest struct {
    someVal string
}

func (this *SomeTest) String() string {
    return this.someVal
}

func main() {
    fmt.Println(&SomeTest{"You can see this now"})
}

任何提供

Stringer
接口 的内容都将使用其 String() 方法进行打印。要实现 stringer,您只需要实现
String() string
。为了做你想做的事,你必须为
Stringer
实现
SomeStruct
(在你的情况下,取消引用
somePointer
并用它来做一些事情)。


2
投票

您正在尝试打印包含指针的结构。当您打印结构体时,它将打印包含的类型的值 - 在本例中是字符串指针的指针值。

您无法取消引用结构体中的字符串指针,因为结构体不再准确地描述它,并且您无法取消引用该结构体,因为它不是指针。

您可以做的是取消引用字符串指针,但不能从结构内部取消引用。

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

输出:

{I want to see what is in here}

您也可以从 Println 中打印特定值:

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

输出:

&{I want to see what is in here}

另一件事要尝试的是 Printf:

func main() {
    structInstance := SomeStruct{&somePointer{"I want to see what is in here"}}
    fmt.Printf("%s",structInstance)
}

输出:

{%!s(*main.somePointer=&{I want to see what is in here})}


0
投票

根据您的用例,

json.Marshal
将为您带来很大帮助。在显示的示例中,需要导出字段:

package main

import (
    "encoding/json"
    "fmt"
)

type SomeStruct struct {
    SomePointer *somePointer
}
type somePointer struct {
    Field string
}

func main() {
    s := SomeStruct{&somePointer{"I want to see what is in here"}}
    b, _ := json.Marshal(s)

    fmt.Println(string(b))
}

// > {"SomePointer":{"Field":"I want to see what is in here"}}```

我的用例是打印从

*sql.Rows Scan
:

返回的不同类型的指针切片
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    i := 1
    s := "foo"
    b := true

    a := []any{&i, &s, &b}

    j, _ := json.Marshal(a)

    fmt.Println(string(j))
}

// > [1,"foo",true]
© www.soinside.com 2019 - 2024. All rights reserved.