How to use an interface containing type constraint as generic

162 Views Asked by At

I want to have a slice of structs with a generic. The generic is an interface with a type constraint.

type constraint interface {
    int32 | uint32
}

type a[T constraint] struct {
    something T
}

type b struct {
    as []a[constraint] // doesn't work
}

How do I make it so i can use both a[int32] and a[uint32] as elements in b.as?

1

There are 1 best solutions below

0
Peirceman On

What I am trying to do is not possible in the way I am proposing. This is because a[int32] and a[uint32] are different types. I need to create an internal interface that only a implements and create an array of that.

type internal interface {
    someObscureMethod()
}

func (anA a[T]) someObscureMethod() {}

type b struct {
    as []internal
}