-2

I have a struct with a large []byte member, that I don't want shown when printed out to the console with fmt.Printf(). So I thought I'd make the member its own type and create a String() for it that returns something short, like 3488 bytes. But it doesn't work. This example:

type anint int

func (me anint) String() string {
    return "I'm anint"
}

type astruct struct {
    theint anint
}

func main() {
    var myint = anint(1)
    fmt.Printf("myint %v\n", myint)

    var mystruct = astruct{myint}
    fmt.Printf("mystruct %v\n", mystruct)
}

Prints out:

myint I'm anint
mystruct {1}

Where I expected:

myint I'm anint
mystruct {I'm anint}

If the toplevel object doesn't have its own String() function, a default reflection-based implementation prints out the data (handy), but it doesn't call String() on members if there is one, which I find surprising.

What am I misunderstanding, and is there any way to use fmt.Sprintf() and friends and get the output I expected?

Peter V. Mørch
  • 11,554
  • 6
  • 59
  • 84
  • 2
    The fmt package can't call methods on unexported members. https://go.dev/play/p/m8rQ2gmE0l9 – Peter May 19 '22 at 08:53

0 Answers0