dongqidi2799 2015-06-13 08:24
浏览 16
已采纳

GoLang等效于使用具有数据和成员函数的接口进行继承

I am a golang newbie so pardon me if there is something obvious I am missing. I have the following structures:

type base interface {
    func1()
    func2()
    common_func()
}

type derived1 struct {
    base // anonymous meaning inheritence
    data DatumType
}

type derived2 struct {
    base // anonymous meaning inheritence
    data DatumType
}

Now I want to do the following:

  1. Keep 'data DatumType' with base in some way so that looking at the definition of base one can know what data is common to all structs.
    1. Implement common_func() in one place so that the derived structs don't need to do it.

I tried implementing the function with the interface but it fails compilation. I tried to create a struct and inherit from that but am not finding good ways to do that. Is there some clean way out ?

  • 写回答

2条回答 默认 最新

  • dqmhgz5848 2015-06-13 09:59
    关注

    Go does not have inheritance. Instead it offers the concept of embedding.

    In this case you don't need/want to define base as an interface. Make it a struct and define the functions as methods. Then embedding base in your derived structs will give them those methods.

    type base struct{
        data DatumType     
    }
    func (b base) func1(){
    
    }
    
    func (b base) func2(){
    
    }
    
    func (b base) common_func(){
    
    }
    
    type derived1 struct {
        base // anonymous meaning embedding
    }
    
    type derived2 struct {
        base // anonymous meaning embedding
    }
    

    Now you can do:

    d := derived1{}
    d.func1()
    d.func2()
    d.common_func()
    

    And (as pointed out by David Budworth in the comment) you can access the fields of base by referring to it's type name like so:

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

报告相同问题?

悬赏问题

  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人