-1

In go code, there is a method to say:

init() {
   service = &Service {
      updater: updaterVariable
   } 
}

updater field has type of *lib.Updater

I am trying to override one method of lib.Updater and pass it to &Service in init method (as above).

What I am doing is:

type ModifiedUpdater struct {
  lib.Updater
}

//overridden method
func (f *ModifiedUpdater) Update(...) { 
  //implementation
}

When I initialize the modified updater and try to pass to Service, I am getting something similar to this "Cannot use variable of *ModifiedUpdater as *Updater"

The way I am trying to assign:

init() {
   modifiedUpd := &ModifiedUpdater{*lib.Updater{conn}}
   service = &Service {
      updater: modifiedUpd
   } 
}
    

How can I fix it or what approach should I take? Thank you.

RustamIS
  • 697
  • 8
  • 24
  • Without the definition of `Service` this cannot be answered. Note that there is **no** inheritance in Go and you **cannot** override methods. – Volker Mar 23 '23 at 06:39

1 Answers1

2

In Go, we do not have inheritance and you can not override methods of structs. To achieve polymorphism you have Interfaces, in your case you should define some

type Updater interface {
   Update(...)
}

then implement this method in some struct

type somestruct struct {
}

func (ss somestruct) Update(...) {
    //do some work
}

and finally, you can use this struct in your init() function

init() {
  service = &Service {
     updater: somestruct{}
  } 
}

your Service should look like this:

type Service struct {
     Updater updater
}
Oto
  • 31
  • 2