阅读pitaya的代码中 发现代码中有相当多的struct 组合 interface
上边日子中就是 TCPAcceptor 这个struct中组合了一个 net.Listener 类型的listener 而net.Listener是一个接口类型
tcpPlayerConn 这个struct里边组合了一个 interface类型的Conn
TcpAcceptor 类型的对象a,a.listener.Accept(),因为不是匿名的,所以要用a.listenter.xxxxx
tcpPlayerConn 类型的对象,可以直接去调用Conn接口里边的方法,
package main
import "fmt"
type InterfaceParent interface {
runParent()
}
type InterfaceChild interface {
InterfaceParent
runChild()
}
type StructParent struct {
name string
}
func NewStructParent(name string) *StructParent {
return &StructParent{name: name}
}
type StructChild struct {
InterfaceChild
*StructParent
age int
}
func NewStructChild(ic InterfaceChild, sp *StructParent, age int) *StructChild {
return &StructChild{
InterfaceChild: ic,
StructParent: sp,
age: age,
}
}
type TestStruct struct {
}
func NewTestStruct() *TestStruct {
return &TestStruct{}
}
func (t *TestStruct) runParent() {
fmt.Println("TestStruct====runParent()")
}
func (t *TestStruct) runChild() {
fmt.Println("TestStruct====runChild()")
}
func main() {
test := NewTestStruct()
parent := NewStructParent("hanmeimei")
child := NewStructChild(test, parent, 10)
fmt.Println(child.name, child.age)
child.runParent()
child.runChild()
fmt.Println("##################################")
child.InterfaceChild.runParent()
child.InterfaceChild.runChild()
}
InterfaceChild 接口 组合了 InterfaceParent接口
TestStruct结构体实现了 InterfaceParent 和 InterfaceChild 接口
运行结果
hanmeimei 10
TestStruct====runParent()
TestStruct====runChild()
##################################
TestStruct====runParent()
TestStruct====runChild()