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
From: <[email protected]> on behalf of Louki Sumirniy
<[email protected]>
Date: Tuesday, August 28, 2018 at 7:16 PM
To: golang-nuts <[email protected]>
Subject: [go-nuts] Does fmt.Print* automatically render an error string in as
struct (play link)
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.
--
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
[email protected]<mailto:[email protected]>.
For more options, visit https://groups.google.com/d/optout.
--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.