Interfaces in Golang
If you’re coming from Java, you definitely know about interfaces. If you’re coming from Python, you’re probably scratching your head. But, no matter which language you’re coming from, you’ll be surprised about how Go implements interfaces.
An interface is a type in Go. But, unlike the struct type, the interface type is not concerned with state, but with behavior.
For example, a Dog struct would look like this:
type Dog struct {
name string
age int
gender string
isHungry bool
}
A Dog interface on the other hand would look like this:
type Dog interface {
barks()
eats()
}
The struct shows us some attributes of a dog, but the interface describes what this dog is supposed to do.
Now, let’s say we’re writing an application about .. well… dogs! We’ll have a lot of different breeds. We know that Go does not support inheritance like OOP languages do , so instead of naming the struct Dog, let’s name it Labrador, and as our app grows, we’ll probably add more breeds.
type Labrador struct {
name string
age int
gender string
isHungry bool
}
For the purpose of our app, we’ll want to split these different dogs into two groups — big dogs and small dogs ( suppose we…