Go Interfaces
Interface is a very powerful tool for achieving duck typings in Go. It enables us to create strong API contract across packages, and create mock for unit testing. Since Go is strongly typed, every function expects a concrete type. For example,
The Feed
function can only feed dogs due to the strong typed nature of the language. One may naturally ask, what if I want to feed a cat?
That obviously does not look good because in practice we would like to write one function that feeds as many animals as possible. So interface
comes to rescue. We define an animal interface.
Any data structure that implements the function Eat
with argument Food
is said to be satisfying the Animal
interface.
Now we just need to modify the argument type of Feed
function a little bit.
Unit Tests
Suppose we want to isolate the Feed
function unit tests from the Animal
unit tests, we can mock the animals!
And then pass it into Feed
and see if test passes.
Last updated