Asegurar que las estructuras integradas implementen la interfaz sin introducir ambigüedad
Estoy tratando de limpiar mi base de código haciendo un mejor trabajo definiendo interfaces y usando estructuras incrustadas para reutilizar la funcionalidad. En mi caso, tengo muchos tipos de entidades que se pueden vincular a varios objetos. Quiero definir interfaces que capturen los requisitos y estructuras que implementan las interfaces que luego pueden integrarse en las entidades.
// 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
}
Entonces, mi primer pensamiento fue que FooLinkerEntity y BarLinkerEntity solo implementaran la interfaz 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
}
Sin embargo, esto termina con un error de ambigüedad para cualquier tipo que pueda vincular Foos y Bars.
// Baz.Identifier() is ambiguous between EntityModel, FooLinkerEntity,
// and BarLinkerEntity.
type Baz struct {
EntityModel
FooLinkerEntity
BarLinkerEntity
}
¿Cuál es la forma correcta de Go para estructurar este tipo de código? ¿Acabo de hacer una aserción de tipo enLinkFoo()
yLinkBar()
para llegar aIdentifier()
yType()
? ¿Hay alguna forma de obtener esta verificación en tiempo de compilación en lugar de tiempo de ejecución?