Go语言中如何实现接口的多继承?

5 min read

在Go语言中,接口是通过继承其他接口来实现多继承的。具体实现步骤如下:

  1. 定义接口A和接口B。

type A interface {
FunctionA()
}

type B interface {
FunctionB()
}

  1. 定义一个新的接口C,继承接口A和B。

type C interface {
A
B
FunctionC()
}

注意:使用关键字“interface”后可在接口定义中使用“{ }”进行多继承。

  1. 实现接口C中的方法。

type MyStruct struct{}

func (s *MyStruct) FunctionA() {
// 实现A接口中的方法
}

func (s *MyStruct) FunctionB() {
// 实现B接口中的方法
}

func (s *MyStruct) FunctionC() {
// 实现C接口中的方法
}

  1. 使用实现了接口C的结构体对象。

var obj C = &MyStruct{}
obj.FunctionA()
obj.FunctionB()
obj.FunctionC()

上述代码中,obj对象实现了接口C,并且可以调用函数A,B和C中的方法。