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

 
  
  
  
 
 
  
 
 
 