Go通过嵌入结构或使用接口支持继承。有不同的方法可以做到这一点,而且每个方法都有一些限制。不同的方式是:
在使用结构体的继承中,基结构体被嵌入到子结构体中,并且基属性和方法可以直接在子结构体上调用。看下面的代码:
package main
import "fmt"
type base struct {
value string
}
func (b *base) say() {
fmt.Println(b.value)
}
type child struct {
base //embedding
style string
}
func check(b base) {
b.say()
}
func main() {
base := base{value: "somevalue"}
child := &child{
base: base,
style: "somestyle",
}
child.say()
//check(child)
}
输出:somevalue
限制:
不支持子类型。不能将子结构体传递给需要base的函数。
例如,在上面的代码中,如果你取消注释//检查(child),它会给出编译错误:“不能使用child(类型*child)作为参数检查的类型基础”。要解决这个问题,我们可以使用接口进行继承