5

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

1 Answer 1

7

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!.

Sign up to request clarification or add additional context in comments.

3 Comments

thansk Steve, indeed it is working already, but I was not expressing my idea properly and I have edited the post, could you please take a look again? thanks
thanks Steve again, but does it mean I have to have separate impl on enrich for each 'sub struct'? but what if enrich will always doing the same thing (assigning ID etc) and would be good if I can reuse it for all 'sub struct'
Now wondering why doing also myA.ID = "A" and myB.ID = "B" in main() crashes it... I.e. how to init a common element, need to add another shared method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.