golang做继承的方法,解决方法
发布时间:2020-12-16 09:25:25 所属栏目:大数据 来源:网络整理
导读:我理解golang不支持继承,但是在下面做什么是正确的方法? type CommonStruct struct{ ID string}type StructA struct{ CommonStruct FieldA string}type StructB struct{ CommonStruct FieldB string}func (s *CommonStruct) enrich(){ s.ID = IDGenerator()
我理解golang不支持继承,但是在下面做什么是正确的方法?
type CommonStruct struct{ ID string } type StructA struct{ CommonStruct FieldA string } type StructB struct{ CommonStruct FieldB string } func (s *CommonStruct) enrich(){ s.ID = IDGenerator() } 如果以下函数,我如何重用代码来丰富所有其他“子结构”? func doSomthing(s *CommoStruct){ s.enrich() } 解决方法
您可以使用界面:
type MyInterface interface { enrich() } func doSomthing(s MyInterface){ s.enrich() } 具有定义的接口的每个功能或方法的任何结构被认为是所述接口的实例.您现在可以使用CommonStruct将任何内容传递给doSomething(),因为CommonStruct定义了enrich().如果要覆盖特定结构的enrich(),只需为该结构定义enrich().例如: type CommonStruct struct{ ID string } type StructA struct{ *CommonStruct } type StructB struct{ *CommonStruct } type MyInterface interface { enrich() } func doSomething(obj MyInterface) { obj.enrich() } func (this *CommonStruct) enrich() { fmt.Println("Common") } func (this *StructB) enrich() { fmt.Println("Not Common") } func main() { myA := &StructA{} myB := &StructB{} doSomething(myA) doSomething(myB) } 打印:
Test it here!. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |