Interfaces Example in Go
If it walks like a duck and it quacks like a duck, then it must be a duck
What’s an interface?
The interface is a custom type used to specify a set of one or more method signatures.
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.
- 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.
- 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
Writeris 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:
main a function is the entry point of the program. It creates the
Human object, and then calls the
DoMove method on each of them.
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.