An Interface in Go defines a behavior. Interfaces are defined with a number of methods that a type must implement. Once the methods are implemented, the type can be used wherever the interface type is needed.
Let’s for example define a Phone
interface:
type Phone interface {
Call()
}
We also define a Nokia
type that implements the Phone interface. We simply need to implement the Call()
function to implement the Phone
interface. Languages such as Java or C# need an explicit statement that they are implementing the interface: public class Nokia implements Phone { }
. In Go you just need to implement the functions:
type Nokia struct {
//...
}
func (n Nokia) Call() {
fmt.Println("Calling someone with my Nokia")
}
Besides the Nokia
we also want an Iphone
:
type Iphone struct {
//...
}
func (n Iphone) Call() {
fmt.Println("Calling someone with my iPhone")
}
Now we define a more generic UseMyPhone
function that will use the Phone
interface:
func UseMyPhone(p Phone) {
p.Call()
}
This allows us to call the UseMyPhone
function with any Phone
type:
n := Nokia{}
i := Iphone{}
UseMyPhone(n)
UseMyPhone(i)
The ability to implement interfaces by just implementing the needed functions is called duck-typing (i.e. signature based polymorphism).