Interfaces and duck typing in Go

Go isn’t object oriented in the typical sense, i.e. if you’re coming from C#, Java or even C++, but it does offer some features which map to features often available in the OO world in one way or another.

For example in a previous post we saw how we created methods that mirror the syntax of methods on objects (or extension methods in C#). We also have interfaces in Go which can include functions.

For example

type Duck interface {
   Quacks()
}

But how do we implement an interface as we cannot include functions in types?

So with our knowledge of methods we will see how we can implement a type that conforms to an interface. As we are not “implementing” or otherwise inheriting from an interface we instead duck type the interface.

Duck typing comes from the phrase – if something looks like a duck, swims like a duck and quacks like a duck then it’s probably a duck.

In programming terms duck typing is the matching of types based upon expected methods and properties rather than upon an expected type. Therefore our Duck interface can be implemented by objects which don’t even need to know about the Duck interface.

For example

type Animal struct {
}

func (a Animal) Quacks() {
   fmt.Println("The animal quacks");
}

function Quack(duck Duck) {
   duck.Quacks()
}

func main() {
   a := Animal{}
   Quack(a)
}

So in the above we’ve declare an Animal type and create a method for the Animal type which is named Quacks (thus fulfilling the requirements of the Duck interface).

Next we have a function which takes a Duck and calls the Quack method on it.

But as you see within main, we’re actually able to pass an Animal type into the function which resolves to Duck because it supports the required interface. Hence duck typing.