Does fmt.Print* automatically render an error string in as struct (play link)

62 views
Skip to first unread message

Louki Sumirniy

unread,
Aug 28, 2018, 8:15:31 PM8/28/18
to golang-nuts
I discovered quite by accident and now I can't find anything saying as such, but this example

package main

import (
  "fmt"
  "errors"
)

type Thing struct {
  err error
}

type thing interface {
  Error() string
}

func (t *Thing) Error() string {
  return t.err.Error()
}

func main() {
  t := new(Thing)
  t.err = errors.New("testing")
  fmt.Println(t)
}

https://play.golang.org/p/xBIGIvSZkqO


as you can see by running it, prints the error value inside the struct. 

I am writing a library where I am using a 'pipeline' model so I can string pointer methods together in a chain, which requires putting an error value inside the structure, and then it does this when I print the struct. It's quite handy but unexpected. I assume if a struct satisfies the error interface it calls it to generate the string.

ma...@degeneration.co.uk

unread,
Aug 28, 2018, 8:44:59 PM8/28/18
to golang-nuts
You have implemented error on *Thing, so it is that which fmt is running, which then in turn runs the implementation from your wrapped error.

If you don't wish fmt to treat your *Thing as an error, you must remove method Error() string from it.

Borman, Paul

unread,
Aug 29, 2018, 7:50:19 AM8/29/18
to Louki Sumirniy, golang-nuts

In your code, anything that implements thing also implements the error interface, which looks just like your thing interface.  Printf knows to use the Error method if it is defined.  See https://play.golang.org/p/JucIqt9H2FF.  You will notice that with your code you can say:

 

var e error = t

 

demonstrating that t is in fact an error (was well as a thing).

 

    -Paul

--
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...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

jake...@gmail.com

unread,
Aug 29, 2018, 11:51:04 AM8/29/18
to golang-nuts
I can't find anything saying as such
 
  From https://golang.org/pkg/fmt/ : "4. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any)."

  As mentioned in another reply, Thing has an Error() method, so it " implements the error interface."
Reply all
Reply to author
Forward
0 new messages