【发布时间】:2020-11-22 15:44:22
【问题描述】:
我需要为一些结构创建继承者:
// Not interface, pure struct
type Base struct {
A int
B string
}
type Child struct {
Base
C bool
}
func (c *Child) SomeLoop() {
for {
// business logic
}
}
创建子实例并从工厂返回
func maker() *Base {
child := &Child {
Base {
A: 1
B: "2"
},
C: false,
}
go child.Some()
return child
}
使用字段 A 和 B 的基本结构从工厂制作的对象
o := maker()
fmt.Println(o.A, o.B)
但我无法从 maker 函数返回 child 作为 base。这种模式如何实现?
【问题讨论】:
-
Go 中没有继承。完全没有。
-
您不能将
*Child作为*Base返回,因为它们是不同的类型。这么多应该很清楚。您要达到的实际目标是什么?可能有更好的方法。 -
您似乎正在将其他语言生态系统的术语应用于 Go。 Go 本身就是一种独特的语言。因此,请告诉我们您想要实现什么样的行为 - 有一种 Go 方法可以做到这一点。
-
我想从少数织物创建对象并存储在切片中
objects := []Base{ makeChild1(), // Child1 的织物 makeCHilds2(), // Child2 的织物 makeChild3 (), // Child3 的结构 } for _, o := range objects { fmt.Println(oA, oB) }基本结构是外部的。我无法从外部包修改 Base 结构。 -
当你说面料时,我很确定你的意思是factory,对吗?
标签: go inheritance factory