我是一个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()
,以便派生结构不需要这样做。
- 在一个位置实现
我尝试使用接口实现该功能,但编译失败。我试图创建一个结构并从中继承,但没有找到很好的方法来做到这一点。有没有干净的出路?
Go 没有继承。相反,它提供了嵌入的概念。
在这种情况下,您不需要/不想将base
定义为interface
。使其成为结构并将函数定义为方法。然后在派生结构中嵌入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
Go 中没有继承。使用组成:
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.