1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
FlamFace
  • 455
  • 4
  • 17
  • This use case seems excessively contrived. Why do you think you need generics here instead of plain interfaces? – blackgreen Feb 08 '23 at 09:30
  • So yes, this usecase is very contrived, however it's an attempt to distil the question into a simple(er) form. It's very possible that simply using interfaces is the right way to go, but partly I was curious as to whether it were indeed possible, or if the implementation of generics in Go simply wouldn't allow something like this. – FlamFace Feb 08 '23 at 09:43
  • Generics are there to reduce the need for concrete types for every argument. `WrappedBar` and `WrappedBarArray` types seems very controversial for the generics perspective. – Eldar Feb 08 '23 at 09:48
  • I'm certainly not trying to be controversial, I'm just trying to figure out the mechanisms by which I can use generics. If I'm understanding correctly, what you're saying is that the idea that the type that is being input to the struct becoming nested further down in fields within fields is not the intended use case? The generic is designed to allow the interface to satisfy the constraint at the top level? – FlamFace Feb 08 '23 at 09:59
  • *I was wondering whether it was possible based on the fields inside* — basically no, but! the answer I posted on the linked question includes a reference to a Go proposal to do just that. In the meantime you have to use methods, or redesign the code – blackgreen Feb 08 '23 at 21:10

0 Answers0