Duck Typing
We have been basically doing what is called duck typing. Duck typing is a test in computer programming: "If it looks like a duck, swims like a duck, and quacks like a duck, then it must be a duck." If a type matches an interface, then you can use that type wherever that interface is used. Duck typing is matching a type based upon methods, rather than the expected type:
type Speaker interface { Â Â Speak() string }
Anything that matches the Speak()
method can be a Speaker{}
interface. When implementing an interface, we are essentially conforming to that interface by having the required method sets:
package main import ( Â Â "fmt" ) type Speaker interface { Â Â Speak() string } type cat struct { } func main() { Â Â c := cat{} Â Â fmt.Println(c.Speak()) } func (c cat) Speak() string { Â Â return "Purr Meow" }
cat
matches the Speak()
method of the Speaker{}
interface, so a cat
is a Speaker...