Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What flag to fmt.Printf to follow pointers recursively?

Tags:

go

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 )

like image 637
Filip Haglund Avatar asked Feb 13 '15 20:02

Filip Haglund


People also ask

What is FMT in Go language?

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.

What does %V mean in Golang?

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.

How do I print a pointer in Go?

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.


1 Answers

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)

like image 148
jatin Avatar answered Jan 01 '23 10:01

jatin