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.
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.
- 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
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…