You want to implement fmt.Formatter <https://pkg.go.dev/fmt?tab=doc#Formatter>. In general I prefer implementing Formatter to either Stringer or GoStringer if I am only doing it for printing, even for the simple cases, as I feel it better reflects the intent. I reserve implementing the String method for when I really do want to be able to access the value programmatically as a string and it is possible to do so in a way that is more efficient than printing it.
On Wed, Jun 24, 2020 at 4:33 PM yves baumes <ybau...@gmail.com> wrote: > When I want to override the '%v' format, I declare a String() method. > When I want to override the '%#v' format, I declare a GoString() method. > > But there is nothing about '%+v'? There is no PlusStringer() method ? > > Let's take the following exemple, the %v and %+v formatter prints the > exact same results. Which is annoying somehow.. > > ``` > package main > > import ("fmt") > > type page struct { > title string > body []byte > } > > func (p *page) String() string { > return fmt.Sprint("{ ", p.title, " ", string(p.body), " }") > } > > func main() { > const title = "helloworld" > const text = "Hello everyone" > p := &page{title: title, body: []byte(text)} > log.Printf("p = %v", p) // prints p = { helloworld Hello everyone } > log.Printf("p = %+v", p) // prints p = { helloworld Hello everyone } > log.Printf("p = %#v", p) // prints p = &main.page{title:"helloworld", > body:[]uint8{0x48, 0x65, 0x6c, [etc] > } > > ``` > > Any clue on how to adapt the String() method to print the fields names? > > > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/2506ab0c-5558-4c72-8ad4-a8ad0006ea08o%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/2506ab0c-5558-4c72-8ad4-a8ad0006ea08o%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAA%3DsxTiLGqBsJh2Kv_PBcCZ0hHZ2zAmLoGibKfbrvtBCR7eeUg%40mail.gmail.com.