gpt4 book ai didi

inheritance - golang 的继承方式,解决方法

转载 作者:IT王子 更新时间:2023-10-29 00:40:36 25 4
gpt4 key购买 nike

我知道 golang 不支持继承,但是在 go for the following 中正确的做法是什么?

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()
}

最佳答案

你可以使用一个接口(interface):

type MyInterface interface {
enrich()
}

func doSomthing(s MyInterface){
s.enrich()
}

任何定义了接口(interface)的每个函数或方法的结构都被认为是所述接口(interface)的实例。您现在可以将带有 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)
}

打印:

Common
Not Common

Test it here! .

关于inheritance - golang 的继承方式,解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25051299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com