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.
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"
})
}
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"})
}
Anything that provides the Stringer
interface will be printed with it's String() method. To implement stringer, you only need to implement String() string
. To do what you want, you'd have to implement Stringer
for SomeStruct
(in your case, dereference somePointer
and do something with that).
You're attempting to print a struct that contains a pointer. When you print the struct, it's going to print the values of the types contained - in this case the pointer value of a string pointer.
You can't dereference the string pointer within the struct because then it's no longer accurately described by the struct and you can't dereference the struct because it's not a pointer.
What you can do is dereference the string pointer, but not from within the struct.
func main() {
pointer := SomeStruct{&somePointer{"I want to see what is in here"}}.somePointer
fmt.Println(*pointer)
}
output: {I want to see what is in here}
You can also just print the specific value from within the Println:
func main() {
fmt.Println(SomeStruct{&somePointer{"I want to see what is in here"}}.somePointer)
}
output: &{I want to see what is in here}
Another thing to try is Printf:
func main() {
structInstance := SomeStruct{&somePointer{"I want to see what is in here"}}
fmt.Printf("%s",structInstance)
}
output: {%!s(*main.somePointer=&{I want to see what is in here})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With