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

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

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

问题

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

  1. init() {
  2. service = &Service {
  3. updater: updaterVariable
  4. }
  5. }

updater字段的类型是*lib.Updater

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

我正在做的是:

  1. type ModifiedUpdater struct {
  2. lib.Updater
  3. }
  4. // 覆盖的方法
  5. func (f *ModifiedUpdater) Update(...) {
  6. // 实现
  7. }

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

我尝试分配的方式是:

  1. init() {
  2. modifiedUpd := &ModifiedUpdater{*lib.Updater{conn}}
  3. service = &Service {
  4. updater: modifiedUpd
  5. }
  6. }

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

英文:

In go code, there is a method to say:

  1. init() {
  2. service = &Service {
  3. updater: updaterVariable
  4. }
  5. }

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:

  1. type ModifiedUpdater struct {
  2. lib.Updater
  3. }
  4. //overridden method
  5. func (f *ModifiedUpdater) Update(...) {
  6. //implementation
  7. }

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:

  1. init() {
  2. modifiedUpd := &ModifiedUpdater{*lib.Updater{conn}}
  3. service = &Service {
  4. updater: modifiedUpd
  5. }
  6. }

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

答案1

得分: 2

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

  1. type Updater interface {
  2. Update(...)
  3. }

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

  1. type somestruct struct {
  2. }
  3. func (ss somestruct) Update(...) {
  4. //做一些工作
  5. }

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

  1. init() {
  2. service = &Service {
  3. updater: somestruct{}
  4. }
  5. }

你的Service应该像这样:

  1. type Service struct {
  2. Updater updater
  3. }
英文:

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

  1. type Updater interface {
  2. Update(...)
  3. }

then implement this method in some struct

  1. type somestruct struct {
  2. }
  3. func (ss somestruct) Update(...) {
  4. //do some work
  5. }

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

  1. init() {
  2. service = &Service {
  3. updater: somestruct{}
  4. }
  5. }

your Service should look like this:

  1. type Service struct {
  2. Updater updater
  3. }

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:

确定