-2

It seems at that at least the default libs for printing, i.e., fmt, can't pretty print unexported fields of structs. There's probably a logical reason for this.

See the following example:

package main

import (
    "fmt"

    "github.com/google/uuid"
)

type foobar struct {
    Name  uuid.UUID
    name2 uuid.UUID
}

func main() {
    foobar1 := foobar{Name: uuid.New(), name2: uuid.New()}

    fmt.Printf("Here is the struct: %+v\n", foobar1)
}

Gives:

Here is the struct: {Name:d5aa42e2-fba9-4f86-8ee9-be2af55d3367 name2:[203 79 55 189 185 158 74 13 134 47 113 136 190 62 49 202]}

Note that field name2 is not pretty-printed using its Stringer interface.

Is the only option to use a String() string function on, in this case, struct foobar ?

I'm trying to do this in the most idomatic way. If it can't be done without heavy logging frameworks and/or reflection, then that's a valid answer as well.

icza
  • 389,944
  • 63
  • 907
  • 827
hbogert
  • 4,198
  • 5
  • 24
  • 38

1 Answers1

3

Quoting from the package doc of fmt:

When printing a struct, fmt cannot and therefore does not invoke formatting methods such as Error or String on unexported fields.

Easiest is to implement String() string on foobar:

func (f foobar) String() string {
    return fmt.Sprint("{Name:", f.Name, " name2:", f.name2, "}")
}

Testing it:

foobar1 := foobar{Name: uuid.New(), name2: uuid.New()}

fmt.Printf("Here is the struct: %+v\n", foobar1)

Output (try it on the Go Playground):

Here is the struct: {Name:b658e3d6-b06e-4ea0-846c-4ff7f80352e7 name2:dfcccba6-242c-4d94-a772-0935796b1dcd}
hbogert
  • 4,198
  • 5
  • 24
  • 38
icza
  • 389,944
  • 63
  • 907
  • 827