dongzhi1851 2017-03-15 06:09
浏览 26
已采纳

继承和接口

I want to express the extends behavior many languages possess.

In my Go Code I have a few structs that look like so:

type Base struct {
        // Some fields
}

type BaseExtender struct {
        Base
        // Unique fields
}

type AnotherBaseExtender struct {
        Base
        // Unique fields
}

Now, I want to write a function that takes any Base since I only need it's "similar fields".

func UseTheBase(b Base) {
        testVal := b.thingICareAbout
}

However, this doesn't work. I've done some digging into interface and thought I could do something like:

type Base interface {
        // Some fields
}

Except it appears that Go automatically infers interfaces by method implementation. Is there a way to mimic this behavior so I can pass any Base into my function, and not have to implement some nop method on the Base struct and all of it's extenders?

Thanks!

  • 写回答

2条回答 默认 最新

  • douhuigan8063 2017-03-15 06:58
    关注

    Base implies you want inheritance in Go, Go deliberately eschews inheritance, don't try to recreate it. You can embed types but think of this as embedding behaviour, not just data (as you might be tempted to in an inheriting language).

    You're on the right lines with your solution but need public methods and yes interfaces are defined in terms of methods. Just define the interface where you call it as:

    type Doer interface {
    DoSomething()
    }
    
    ...
    func doit(d Doer) {
       d.DoSomething()
    }
    

    doit doesn't care what its argument is as long as it has a DoSomething method. Obviously this is a trivial example and there's no point in it, but if you need to override something in all extenders, ask yourself why Base exists, if it is just to add some fields, that's probably not enough reason for a separate type, just add the fields where you need them.

    Try to avoid the vast taxonomies of types that you might construct in other languages.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么