function as an interface
“An interface type is defined as a set of method signatures.”
Taking a simple example:
|
|
golang nameing convention is interfaces that end in er
, Reader, Writer, Closer etc..
In this example, the interface Fooer
defines a single method Foo
, any struct with a method Foo
will implement this interface, (implementation is done implicitly).
|
|
But it’s not just structs that can implement interfaces, if an interface has a single method, then you can implement it with a function type.
|
|
But why? If you define your more complex behaviours and interfaces by embedding smaller interfaces with smaller method sets, then creating the implementations of those interfaces becomes significantly easier. You can now mock or implemet behaviours with an anonymous function instead of a mock or no op struct.
|
|
Here the type bFoo
implemets the interface Fooer
and any anonymous function that has the same method signature as Fooer
can be cast to bFoo
and it too will implement the Fooer
interface.
This means less code and cleaner code as once you have the type bFoo
any function can implement Fooer
without the need for a struct for it to be a method upon.
Runnable example: https://play.golang.org/p/bVp8Lljxkj
Now if you have a complex struct like:
|
|
You can implement the foo Fooer
field with just an anonymous function.