接口的组合(类似Java中接口的多继承)
在GO中,接口的组合,类似于Java中接口的多继承.
接着 上一篇继续定义两个接口:
//定义一个post的接口
type Poster interface {
Post(url string,params map[string]string)string
}
//接口组合: 定义一个 session接口
type Session interface {
Poster
Retriever
}
在mook.Retriever里实现Post方法:
package mook
type Retriever struct {
Contents string
}
func (r *Retriever) Post(url string, params map[string]string) string {
r.Contents = params["contents"]
return "ok"
}
func (r *Retriever) Get(url string) string {
return r.Contents
}
//定义一个session方法
func session(s Session) string {
s.Post("http://www.imooc.com", map[string]string{"contents":"another a fake imooc.com"})
s.Get("http://www.imooc.com")
return "ok"
}
//定义一个方法,传入poster接口类型
func post(poster Poster) string {
return poster.Post("http://www.imooc.com", map[string]string{"contents":"another a fake imooc.com"})
}
func main() {
retriever := &mook.Retriever{"this is a fake imooc.com"}
var r Retriever = retriever
var p Poster = retriever
download(retriever)
post(retriever)
session(retriever)
}
根据main方法里的实验,我们看到,因为mook.Retriever实现了Post方法,所以在GO语言体系中,其是接口类型Retriever
也是Poster
又是Session
.
三个方法均可使用mook.Retriever{"this is a fake imooc.com"}
传入.
接口的组合也非常的简单,直接将接口名写入接口内部即可,且还可以在接口内再定义自己的接口方法.
作者所有的学习源码在 go学习源码github地址,如果觉得有用的话帮小智贡献一个star😁