main函数入口
package main import ( "fmt" "learngo/retriever/mock" "learngo/retriever/real" "time" ) func main(){ var r Retriever retriever := mock.Retriever{"this is fyf"} inspect(r) r = &real.Retriever{ UserAgent:"Mozilla/5.0", TimeOut:time.Minute, } inspect(r) //Type assertion reaRetriever:=r.(*real.Retriever) fmt.Println(reaRetriever.TimeOut) //fmt.Println(download(r)) fmt.Println(session(&retriever)) } //interface中的函数不用加func type Retriever interface { Get(url string) string } type Poster interface { Post(url string ,form map[string]string) string } const url = "http://www.imooc.com" func post(p Poster){ p.Post(url,map[string]string{ "name":"fyf", "cource":"golang", }) } //组合interface,RetrieverPoster内部装了两个interface type RetrieverPoster interface { Retriever Poster } func session (r RetrieverPoster) string{ r.Post(url,map[string]string{ "contents":"this is another", }) return r.Get(url) } func download(r Retriever) string{ return r.Get(url) } func inspect(r Retriever){ fmt.Printf("%T %v ",r,r) switch v:=r.(type) { case *mock.Retriever: fmt.Println("Contents",v.Contents) case *real.Retriever: fmt.Println("UserAgent",v.UserAgent) } }
实现了两个接口
package mock import "fmt" type Retriever struct { Contents string } func (r *Retriever) String() string { return fmt.Sprintf("Retriever:{Contents=%s}",r.Contents) } //接口1 func (r *Retriever) Post(url string, form map[string]string) string { r.Contents = form["contents"] return "ok" } //go语言中实现了Get(url string),就被认为实现了Retriever接口
//接口2 func (r *Retriever) Get(url string) string { return r.Contents }