Interfaces Example in Go

If it walks like a duck and it quacks like a duck, then it must be a duck

Jerry An
2 min readJan 20, 2022


What’s an interface?

The interface is a custom type used to specify a set of one or more method signatures.

For example:

type Reader interface {
Read(p []byte) (n int, err error)

The Reader is an interface that defines a method signature for reading data. This method takes a byte slice and returns the number of bytes read.

There are some essential points related to the interface.

  1. An interface is a way to define a contract between a set of objects. The contract is a set of methods signatures that the objects must implement.
  2. An interface type can be defined as a (derived) named type. The identifier after the interface keyword is the name of the interface type. For example, the Writer is the name of an interface type.

An Animal Interface Example

In this example, we define an interface called Mover. It has only one method signatures Move(). Three types implement this interface:Dog, Cat ,Human.

The main a function is the entry point of the program. It creates the Dog, Cat, and Human object, and then calls the DoMove method on each of them.

The method DoMove is straightforward. It takes in an interface object and then calls the Move method on that object. Here we realize the concept of polymorphism in Go. Which is a core concept in OOP.



Jerry An

Golang/Python developer. Buy me a coffee: