GOLANG

Interfaces in Go

Interfaces in Go do not enforce a type to implement methods but interfaces are very powerful tools. A type can choose to implement methods of an interface. Using interfaces, a value can be represented in multiple types, AKA, polymorphism.

Uday Hiwarale
RunGo
Published in
14 min readOct 21, 2018

--

(source: pexels.com)

What is an interface?

We talked a lot about the object and behavior in the structs and methods lessons. We also saw how a structure (and other types) can implement methods. An interface is another piece of a puzzle that brings Go close to the Object-Oriented programming paradigm.

An interface is a collection of method signatures that a Type can implement (using methods). Hence interface defines (not declares) the behavior of the object (of the type Type).

For example, a Dog can walk and bark. If an interface defines method signatures for walk and bark while Dog implements walk and bark methods, then Dog is said to implement that interface.

The primary job of an interface is to provide only method signatures consisting of the method name, input arguments and return types. It is up to a Type (e.g. struct type) to declare methods and implement them.

If you are an OOP programmer, you might have used implement keyword a lot while implementing an interface. But in Go, you do not explicitly mention if a type implements an interface.

If a type implements a method with name and signature defined in an interface, then that type implements that interface. Like saying if it walks like a duck, swims like a duck and quacks like a duck, then it’s a duck.

Declaring interface

Like struct, we need to create a derived type to simplify interface declaration using the keyword interface.

type Shape interface {
Area() float64
Perimeter() float64
}

💡 The naming convention of interfaces in Go is a little bit tricky, you can follow this Medium article for more information. If you want to go with I prefix or Interface suffix, then that’s fine too. Just keep it consistent.

--

--