golang做继承的方法,解决方法

Joh*_*ohn 4 inheritance go

我理解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()
}
Run Code Online (Sandbox Code Playgroud)

如果以下函数,我如何重用代码来丰富所有其他"子结构"?

func doSomthing(s *CommoStruct){
  s.enrich()
}
Run Code Online (Sandbox Code Playgroud)

Ste*_* P. 6

您可以使用界面:

type MyInterface interface {
    enrich()
}

func doSomthing(s MyInterface){
  s.enrich()
}
Run Code Online (Sandbox Code Playgroud)

具有定义的接口的每个功能或方法的任何结构被认为是所述接口的实例.您现在可以传递带有CommonStructto的任何内容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)
}
Run Code Online (Sandbox Code Playgroud)

打印:

常见
不常见

在这里测试吧!.