I've looked in the documentation and couldn't find this info. Given a struct, is it possible to implement a method (say, func (k Koala) String() string
) that will automatically be used by the fmt.Print
family when printing a struct? Maybe there's an interface somewhere, but I didn't find it.
Yes, it's called fmt.Stringer()
Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.
type Stringer interface { String() string }
The *print*
functions don't accept a Stringer()
interface themselves because fmt.Println("foo")
and fmt.Println(someStringer)
are equally valid. I recommend you go through the print.go
source code to see exactly how this works, but in brief the *print*
functions:
interface{}
;string
, int
, etc.) and format it accordingly if it is;.String()
method and use that if it exists.The precise logic is a bit more involved. As mentioned, I encourage you to go through the source code yourself. It's all just plain readable Go.