欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > go语言中interface之间嵌入与struct之间的嵌入实现多态

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

2025/5/3 1:36:21 来源:https://blog.csdn.net/canyuemanyue/article/details/143314733  浏览:    关键词:go语言中interface之间嵌入与struct之间的嵌入实现多态

前言

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

一、接口interface的定义

// 基本接口
type BaseInterface interface {Method1()
}// 第一个扩展接口
type Interface1 interface {BaseInterfaceMethod2()
}// 第二个扩展接口
type Interface2 interface {BaseInterfaceMethod3()
}

二、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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词