【发布时间】:2016-04-19 06:30:43
【问题描述】:
我正在尝试通过更好地定义接口和使用嵌入式结构来重用功能来清理我的代码库。就我而言,我有许多可以链接到各种对象的实体类型。我想定义接口来捕获实现接口的需求和结构,然后可以嵌入到实体中。
// All entities implement this interface
type Entity interface {
Identifier()
Type()
}
// Interface for entities that can link Foos
type FooLinker interface {
LinkFoo()
}
type FooLinkerEntity struct {
Foo []*Foo
}
func (f *FooLinkerEntity) LinkFoo() {
// Issue: Need to access Identifier() and Type() here
// but FooLinkerEntity doesn't implement Entity
}
// Interface for entities that can link Bars
type BarLinker interface {
LinkBar()
}
type BarLinkerEntity struct {
Bar []*Bar
}
func (b *BarLinkerEntity) LinkBar() {
// Issues: Need to access Identifier() and Type() here
// but BarLinkerEntity doesn't implement Entity
}
所以我的第一个想法是让 FooLinkerEntity 和 BarLinkerEntity 只实现 Entity 接口。
// Implementation of Entity interface
type EntityModel struct {
Id string
Object string
}
func (e *EntityModel) Identifier() { return e.Id }
func (e *EntityModel) Type() { return e.Type }
type FooLinkerEntity struct {
EntityModel
Foo []*Foo
}
type BarLinkerEntity struct {
EntityModel
Bar []*Bar
}
但是,对于可以链接 Foos 和 Bars 的任何类型,这最终会导致模棱两可的错误。
// Baz.Identifier() is ambiguous between EntityModel, FooLinkerEntity,
// and BarLinkerEntity.
type Baz struct {
EntityModel
FooLinkerEntity
BarLinkerEntity
}
构建此类代码的正确 Go 方法是什么?我是否只是在LinkFoo() 和LinkBar() 中进行类型断言以获取Identifier() 和Type()?有没有办法在编译时而不是运行时得到这个检查?
【问题讨论】:
-
为什么是
FooLinkerEntity doesn't implement Entity?似乎FooLinkerEntity是Entity的子类型 -
Enitty 是 FooLinkerEntity 不直接实现的接口(或者如果它实现了,我最终会出现歧义错误)。
-
我知道它现在没有实现,但我的意思是,正如你所说的
All entities implement this(Entity ) interface,为什么不让它实现Entity接口呢?或者您可以发布一个完整的代码以使细化更清晰。 -
这就是整个问题。看看上面的 Baz 结构。如果我让 FooLinkerEntity 和 BarLinkerEntity 实现 Entity 接口,我不能再将它们嵌入到其他实体中而不会产生歧义问题。 FooLinkerEntity 永远不会单独使用,我只是用它来封装可以嵌入到其他实体中的功能。
标签: oop go interface composition embedding