I'm having trouble printing a struct when failing test cases. It's a pointer to a slice of pointers to structs, or *[]*X
. The problem is that I need to know the contents of the X
-structs inside the slice, but I cannot get it to print the whole chain. It only prints their addresses, since it's a pointer. I need it to follow the pointers.
This is however useless since the function I want to test modifies their contents, and modifying the test code to not use pointers just means I'm not testing the code with pointers (so that wouldn't work).
Also, just looping through the slice won't work, since the real function uses reflect and might handle more than one layer of pointers.
Simplified example:
package main
import "fmt"
func main() {
type X struct {
desc string
}
type test struct {
in *[]*X
want *[]*X
}
test1 := test{
in: &[]*X{
&X{desc: "first"},
&X{desc: "second"},
&X{desc: "third"},
},
}
fmt.Printf("%#v", test1)
}
example output:
main.test{in:(*[]*main.X)(0x10436180), want:(*[]*main.X)(nil)}
(code is at http://play.golang.org/p/q8Its5l_lL )
fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output.
The verb %v ('v' for 'value') always formats the argument in its default form, just how Print or Println would show it. The special verb %T ('T' for 'Type') prints the type of the argument rather than its value. The examples are not exhaustive; see the package comment for all the details.
In Go, to print the memory address of a variable, struct, array, slice, map, or any other structure, you need to generate a pointer to the value with the address operator & and use the fmt. Println() function (or any other print function from the fmt package) to write the value address to the standard output.
I don't think fmt.Printf has the functionality you are looking for.
You can use the https://github.com/davecgh/go-spew library.
spew.Dump(test1)
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