0
点赞
收藏
分享

微信扫一扫

go语言中interface之间嵌入与struct之间的嵌入实现多态

楚木巽 2024-11-06 阅读 9

前言

在Go语言中,结构体(struct)之间可以相互包含,这种特性通常称为“嵌入”(embedding)。当你在一个结构体中嵌入另一个结构体时,被嵌入的结构体的字段和方法就像它们直接声明在新结构体中一样。接口可以组合其他接口,一个接口可以包含另一个或多个接口的所有方法。

一、接口interface的定义

// 基本接口
type BaseInterface interface {
    Method1()
}

// 第一个扩展接口
type Interface1 interface {
    BaseInterface
    Method2()
}

// 第二个扩展接口
type Interface2 interface {
    BaseInterface
    Method3()
}

二、struct实例化interface 

type MyStruct struct{}

func (m MyStruct) Method1() {
    fmt.Println("Base method called")
}

// 实现第一个扩展接口的结构体
type MyStruct1 struct {
    MyStruct
}

func (m MyStruct1) Method1() {
    fmt.Println("MyStruct1's Method1 called")
}

func (m MyStruct1) Method2() {
    fmt.Println("Method2 called")
}

// 实现第二个扩展接口的结构体
type MyStruct2 struct {
    MyStruct
}

func (m MyStruct2) Method1() {
    fmt.Println("MyStruct2's Method1 called")
}

func (m MyStruct2) Method3() {
    fmt.Println("Method3 called")
}

三、公共函数调用接口方法 

func commonFunction(b BaseInterface) {
    b.Method1()
}

各个struct实现了各自的Method1方法,当传入对应结构体参数时相应执行对应的函数。

四、主函数调用 

func main() {
    s1 := MyStruct1{}
    s2 := MyStruct2{}

    commonFunction(s1)
    commonFunction(s2)
举报

相关推荐

0 条评论