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