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

时间:2014-01-07 20:12:25

标签: go printf

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

4 个答案:

答案 0 :(得分:15)

有一个名为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"
 })
}

答案 1 :(得分: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 interface的任何内容都将使用它的String()方法打印。要实现stringer,您只需要实现String() string。要执行您想要的操作,您必须为Stringer实施SomeStruct(在您的情况下,取消引用somePointer并对其执行某些操作)。

答案 2 :(得分: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})}

答案 3 :(得分:0)

如果您可以将字段的首字母更改为大写,则可以使用encoding/json包将对象转换为json字符串并打印json。这是示例代码:

package main

import (
    "fmt"
    "encoding/json"
)

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

func main() {
    ss := SomeStruct{&somePointer{"I want to see what is in here"}}
    s, _ := json.MarshalIndent(ss, "", "\t")
    // s, _ := json.Marshal(ss) // marshal without line and space
    fmt.Println(string(s))
}

这将打印以下消息:

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