Inheritance 使用数据和成员函数接口的GoLang等效继承

Inheritance 使用数据和成员函数接口的GoLang等效继承,inheritance,go,Inheritance,Go,我是golang新手,如果有明显的遗漏,请原谅。我有以下结构: type base interface { func1() func2() common_func() } type derived1 struct { base // anonymous meaning inheritence data DatumType } type derived2 struct { base // anonymous meaning inheritence

我是golang新手,如果有明显的遗漏,请原谅。我有以下结构:

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
}
现在我想做以下工作:

  • 以某种方式将“
    data DatumType
    ”与
    base
    保持在一起,这样查看
    base
    的定义就可以知道所有结构共有哪些数据。
  • 在一个位置实现
    common_func()
    ,这样派生结构就不需要这样做

  • 我尝试用接口实现函数,但编译失败。我试图创建一个结构并从中继承,但没有找到好的方法。有干净的出路吗?

    围棋没有继承权。使用组合:

    type common struct {
        data DatumType
    }
    
    func (c *common) commonFunc() {
        // Do something with data.
    }
    
    type derived1 struct {
        common
        otherField1 int
    }
    
    // Implement other methods on derived1.
    
    type derived2 struct {
        common
        otherField2 string
    }
    
    // Implement other methods on derived2.
    

    Go没有继承权。相反,它提供了一个新的概念

    在这种情况下,您不需要/不想将
    base
    定义为
    接口
    。将其设为结构,并将函数定义为方法。然后在派生结构中嵌入
    base
    ,将为它们提供这些方法

    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
    }
    
    现在您可以执行以下操作:

    d := derived1{}
    d.func1()
    d.func2()
    d.common_func()
    
    并且(正如David Budworth在评论中指出的那样),您可以通过引用其类型名称来访问
    base
    的字段,如下所示:

    d.base.data = something
    

    在您的结构中有这样一个匿名接口成员可能不是您想要的。它将使您的结构实现接口,但可能不是以您认为的方式。任何未在结构上实现的接口方法最终都将委托给此成员。如果您将其设置为
    nil
    ,那么您已经将可能是一个简单的编译错误转变为运行时错误。感谢@JamesHenstridge的注释。根据许多在线资源,我认为这是推荐的方法。有名字会让它看起来很难看。那为什么要用-1呢?请添加一个注释。@JamesHenstridge:如果基函数有所有方法的默认实现,则您提到的问题应该不会发生,对吗?接口没有实现。把它想得更像是java接口(不需要显式地声明它),而不是C++类,它有几个抽象的虚拟方法。你不必用嵌入的结构来命名它,因为你可以通过类型的名称来访问它(在这种情况下,D.BaseDATA)。例子:Tks,我不知道!我链接的“有效围棋”部分中确实提到了这一点,但我没有从中了解到这适用于任何领域。很高兴知道。据此编辑了我的答案。