I want to define a mechanism whereby I have a struct that contains a slice of a wrapped generic type, and allow for different implementations of said wrapped generic type.
My code looks something like this currently:
type Foo interface {
Bar()
}
type WrappedFoo[FooArg Foo] struct {
Foo Foo
}
type WrappedFooArray[FooArg Foo] struct {
Foos []WrappedFoo[FooArg]
}
type Bar struct{}
func (Bar) Bar() {}
type WrappedBar WrappedFoo[Bar]
type WrappedBarArray WrappedFooArray[Bar]
func main() {
bars := []WrappedBar{
{
Foo: Bar{},
},
}
ba := WrappedBarArray{
Foos: bars,
}
fmt.Printf("%v", ba)
}
And I'm getting an error of something like
cannot use bars (variable of type []WrappedBar) as []WrappedFoo[Bar] value in struct literal
This makes sense to me, as WrappedBar
is a concrete type and different from WrappedFoo[Bar]
.
If I change the Bars slice that I pass into the WrappedBarArray to be of type WrappedFoo[Bar]
then it works. But it would be nice to have a concrete type that satisfies this constraint purely by its nature. I suppose I could define an interface for it, and have a method specifically to declare that it satisfies the constraint, but I was wondering whether it was possible based on the fields inside.
Any guidance would be greatly appreciated.