今天用golang写通用组件发现类之间不能继承

type A struct{

}

type B struct{
    A
}

func test(a A){
    fmt.Println(a)
}

func main() {
	fmt.Println("Hello, playground")
	var a = A{}
	var b = B{}
	test(a)
	test(b)
}

上面的代码会报错,显示不能将 B 类对象当作参数传给 test,也就是说虽然 b 可以调用 a 类的方法,但是 b 和 a 之间是不存在继承关系的。

如果想要实现多态需要用 interface。

我发现有两种 interface 的实现方法,如果对应 Python 的话,一种是白鹅类型,一种是鸭子类型:

  • 白鹅类型:对接口有明确规定,需要通过继承获得
  • 鸭子类型:没有明确接口,只要满足协议即可

白鹅类型:

把 interface 类写在 struct 里面,显示继承接口

type Base interface{

}

type A struct{
    Base
}

type B struct{
    Base
}

func test(a Base){
    fmt.Println(a)
}

func main() {
	fmt.Println("Hello, playground")
	var a = A{}
	var b = B{}
	test(a)
	test(b)
}

鸭子类型:

不需要显示继承,实现对应协议即可

type Base interface{
    protocol()
}

type A struct{
    Base
}

func (a A) protocol(){

}

type B struct{
    Base
}

func (b B) protocol(){

}


func test(a Base){
    fmt.Println(a)
}

func main() {
	fmt.Println("Hello, playground")
	var a = A{}
	var b = B{}
	test(a)
	test(b)
}

而且我发现可以通过白鹅类型让接口继承接口

type Basebase interface{

}

type Base interface{
    Basebase
}

type A struct{
    Base
}

type B struct{
    Base
}

func test(a Basebase){
    fmt.Println(a)
}

func main() {
	fmt.Println("Hello, playground")
	var a = A{}
	var b = B{}
	test(a)
	test(b)
}