duck typeing
隐式的实现接口的方法就等于实现了接口
main函数
package main import ( "fmt" "learngo/retriever/mock" "learngo/retriever/real" ) func main(){ var r Retriever r = mock.Retriever{"this is fyf"} r = real.Retriever{} fmt.Println(download(r)) } //interface中的函数不用加func type Retriever interface { Get(url string) string } func download(r Retriever) string{ return r.Get("http://www.imooc.com") }
实现接口一
package mock type Retriever struct { Contents string } //go语言中实现了Get(url string),就被认为实现了Retriever接口 func (r Retriever) Get(url string) string { return r.Contents }
实现接口二(拿下慕课网首页)
package real import ( "time" "net/http" "net/http/httputil" ) type Retriever struct { UserAgent string TimeOut time.Duration } func (r Retriever) Get(url string) string { resp , err :=http.Get(url) if err != nil{ panic(err) } result,err := httputil.DumpResponse(resp,true) resp.Body.Close() if err != nil { panic(err) } return string(result) }