davecgh / go-spew

Implements a deep pretty printer for Go data structures to aid in debugging
ISC License
5.98k stars 361 forks source link

Output valid Go code initializing structs #80

Closed AshKash closed 6 years ago

AshKash commented 6 years ago

Is is possible to output valid Go code that initialize a struct with pointers that can be used in tests? I am printing a large struct (with pointer members) received back as part of a Protobuf response. Trying to use this data to initialize test data. Converting this using fmt.Printf("%#v") does not chase down pointers -- otherwise the format is just perfect. spew uses a different format and I cannot use that.

type Y struct {
    Y1 *string
    Y2 *int32
}

If these are assigned values "str" and 42, then the output should be something like:

Y{ Y1:&[]string{"str"}[0], Y2:&[]int32{42}[0] }

It should also bypass the stringer methods so that field names are used and not struct tagnames etc.

jrick commented 6 years ago

I'm aware of (but have not used) https://github.com/shurcooL/go-goon which is a fork of spew that outputs Go expressions, but I'm not sure exactly how it deals with pointers and cycles.

AshKash commented 6 years ago

Thanks! It prints this:

(Y)(Y{
    Y1: (*string)(&"str"),
    Y2: (*int32)(&42),
})

which is not valid Go code.