After covering methods, we must cover interfaces, which make use of methods to produce efficient and scalable code in the Go language.
An interface can be very simply described as a Go type that hosts a collection of methods.
Here is a simple example:
type MyInterface interface{
GetName()string
GetAge()int
}
The preceding interface defines two methods—GetName() and GetAge().
Earlier, we attached two methods with the same signature to a type called Person:
type Person struct{
name string
age int
}
func (p Person) GetName()string{
return p.name
}
func (p Person) GetAge()int{
return p.age
}
In Go, an interface can be implemented by other types, like Go structs. When a Go type implements an interface, a value of the interface type can then hold that Go type data. We'll see what that means very shortly.
A very special feature in Go is the fact that for...