Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang way to do inheritance, the workaround

Tags:

inheritance

go

I understand golang does not support inheritance, but what is the right way to do in 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()
}

how I can reuse the code in enrich for all other "sub struct" if the following function?

func doSomthing(s *CommoStruct){
  s.enrich()
}
like image 472
John Avatar asked Mar 18 '23 21:03

John


1 Answers

You can use an interface:

type MyInterface interface {
    enrich()
}

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

Any struct that has each of the functions or methods of an interface defined is considered an instance of said interface. You could now pass anything with a CommonStruct to doSomething(), since CommonStruct defined enrich(). If you want to override enrich() for a particular struct, simply define enrich() for that struct. For example:

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

Prints:

Common
Not Common

Test it here!.

like image 144
Steve P. Avatar answered Mar 28 '23 01:03

Steve P.