method overriding, embedding and pointer in golang. Can not assign embedded variable

huangapple go评论84阅读模式
英文:

method overriding, embedding and pointer in golang. Can not assign embedded variable

问题

在Go代码中,有一种方法可以这样说:

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

updater字段的类型是*lib.Updater

我正在尝试覆盖lib.Updater的一个方法,并将其传递给init方法中的&Service

我正在做的是:

type ModifiedUpdater struct {
  lib.Updater
}

// 覆盖的方法
func (f *ModifiedUpdater) Update(...) { 
  // 实现
}

当我初始化修改后的更新器并尝试传递给Service时,我得到了类似于"Cannot use variable of *ModifiedUpdater as *Updater"的错误。

我尝试分配的方式是:

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

我该如何修复它或者应该采取什么方法?
谢谢。

英文:

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.

答案1

得分: 2

在Go语言中,我们没有继承,并且无法重写结构体的方法。为了实现多态性,我们可以使用接口。在你的情况下,你应该定义一个接口类型:

type Updater interface {
   Update(...)
}

然后在某个结构体中实现这个方法:

type somestruct struct {
}

func (ss somestruct) Update(...) {
    //做一些工作
}

最后,在你的init()函数中可以使用这个结构体:

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

你的Service应该像这样:

type Service struct {
     Updater updater
}
英文:

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
}

huangapple
  • 本文由 发表于 2023年3月23日 14:04:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75819672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定