douhan9748 2014-08-11 12:50
浏览 40
已采纳

嵌入式结构的覆盖行为

I have a type XY that has various fields and methods (a few dozen).

type XY struct {
    Name      string
    SomeValue int
    ...
}

func (xy *XY) Do1() { ... }
func (xy *XY) Do2() { ... }
func (xy *XY) Do3() { ... }
...

Now I want to define a second type that embeds XY, keeping all fields and methods. But I do want to modify a few functions.

type AB struct {
    XY
}

func (ab *AB) Do2() { ... }

So far so good. Now I want to pass AB to a function that takes XY.

func SomeFunc(xy *XY) { ... }

And here's where I stumble, no polymorphism.

I can pass *AB.XY to the function, but that wouldn't make use of AB's Do2 function anymore. I could make an interface for it, which is probably the intended way, but if SomeFunc were to need near to all functions of XY, say getters of almost all fields, I'd basically need to create a copy of XY, as an interface (possible use case: I'm on a server and have to send values to a client in a specific way). I wouldn't want to only make it an interface, because I'd have to redefine all fields and functions in all types that are using the interface.

I can think of solutions for this problem, e.g. making Do2 a closure, that is set depending on the "host" type, or an enum field in XY and changing the behavior of Do2 based on that "type" variable, or using reflection and interface{} in SomeFunc, but I'd like to know what the "correct" way in Go would be. How do you do this in the most efficient way, even if you have a lot of functions?

  • 写回答

2条回答 默认 最新

  • donglu2761 2014-08-11 12:58
    关注

    The correct way to do it in Go is to use interfaces. Create an interface of Do1, Do2, etc. and make SomeFunc work with the interface type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000