
上QQ阅读APP看书,第一时间看更新
Duck typing
Go does not have inheritance or subtypes, but we have interfaces. Functions that implement the methods of an interface satisfy the interface contract implicitly.
Go supports what's called duck typing. If it walks like a duck and quacks like a duck, then it's a duck. In other words, if we have a Go struct with methods that implement the Duck interface, that is, if it has the Walk() and Quack() methods, then for all intents and purposes, our struct is a duck.
In object-oriented languages, such as Java, we'd be tempted to design our ducks as follows.