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,
funcFeed(d*Dog)bool{// Return true if the dog accepts the feeding, else return false.}
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.
typeFoodstruct{}typeAnimalinterface{Eat(Food)}
Any data structure that implements the function Eat with argument Food is said to be satisfying the Animal interface.