How to dereference fields when printing?

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

This prints a memory address like this {0x10500168}

Is there a way to make it print:

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

This is mostly for debugging purposes, if I had a struct with 30 pointer fields, I didn’t want to have to do a println for each of the 30 fields to see what is in it.

1 Like

There is a great package called go-spew. Does exactly what you want.

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)

}

Will give you this output:

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

Refer: how-to-dereference-fields-when-printing