- “像鸭子走路,像鸭子叫(长得像鸭子),那么就是鸭子”
- 描述事物的外部行为而非内部结构
- 严格说go属于结构化类型系统,类似dock typing
先看一个其他语言中的duck typing :
-
python中的duck typing``` def download(retriever): return retriever.get("www.fabric.com")
1* 运行时才知道传入的retriever有没有get 2* 需要注释说明接口 -
c++中的duck typing
1template <class R> 2string download(const R& retriever) { 3 return retriever.get("www.fabric.com"); 4}-
编译时才知道传入的 有没有get
-
需要注释说明接口
-
-
java中的类似代码
1<R extends Retriever> 2String download(R r) { 3 return r.get("www.fabric.com"); 4}-
传入的参数必须实现Retriever接口
-
不是duck typing
-
-
go语言中的duck typing
-
接口由使用者定义,谁用谁定义
1// 实现者 2package fake 3 4type Retriever struct{ 5 Contents string 6} 7 8func (r Retriever) Get(url string) string { 9 return r.Contents 10} 11 12// 使用者 13type Retriever interface { 14 Get(url string) string 15} 16 17func download(r Retriever) string { 18 return r.Get("https://www.hyperledger.org/") 19} 20 21func main() { 22 var r Retriever 23 r = fake.Retriever{"this is a fake fabric.com"} 24 fmt.Println(download(r)) 25 // 等价于 26 // fmt.Println(download( 27 // fake.Retrivever{ 28 // "this is a fake fabric.com"})) 29}
-
本文转自 https://blog.csdn.net/qq_37858332/article/details/99715083,如有侵权,请联系删除。
