Interfaces
Interfaces are a duck typing feature.
Contents
Implementation
An interface is written as:
type Duck interface {
Walk(int)
Quack() string
}This is then implemented like:
type Mallard struct {
bornAt int
position int
}
func (m *Mallard) Walk(meters int) {
m.position += meters
}
func (m *Mallard) Quack() string {
return "quack!"
}
type Muscovy struct {
bornAt int
position int
}
func (m *Muscovy) Walk(meters int) {
m.position += meters
}
func (m *Muscovy) Quack() string {
return "quack!"
}
Use Cases
Any object that implements the receiver methods Walk() and Quack() is, for purposes of typing, a Duck.
// As a struct member.
type Coop struct {
ducks []Duck
}
func (c *Coop) HatchNew(species string) {
if species == "mallard" {
c.ducks = append(c.ducks, Mallard{0})
} else {
c.ducks = append(c.ducks, Muscovy{0})
}
}
// As a function argument.
func Report(duck Duck) {
fmt.Printf("I have walked %d meters", duck.position)
}
Invalid Uses
Note that something like the following is forbidden.
func (d Duck) Greet() {
println("quack!")
}Interfaces cannot be a receiver type.
