I have been reading about function types as interface values in go and I came across an example that I have not been able to figure out. Here it is:
type binFunc func(int, int) int
func add(x, y int) int { return x + y }
func (f binFunc) Error() string { return "binFunc error" }
func main() {
var err error
err = binFunc(add)
fmt.Println(err)
}
You can find it on Go Playground here.
I understand that you can assign a method to a function type, but I do not understand how Error()
is being called.
The docs for the fmt package have this to say:
Except when printed using the verbs
%T
and%p
, special formatting considerations apply for operands that implement certain interfaces. In order of application:...
If the format (which is implicitly
%v
forPrintln
etc.) is valid for a string (%s %q %v %x %X
), the following two rules apply:
- If an operand implements the
error
interface, theError
method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).- If an operand implements method
String() string
, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).
In other words, fmt.Println
will attempt to print the string representation of the interface. Since the error interface is satisfied by binFunc
, it invokes the Error
method of binFunc
.