1

I've tried to implement a generic Set in go 1.18. I've used a map from the generic type to bool to implement it. this requires me to add the builtin constraint comparable to the type parameter:

type Set[T comparable] struct {
    values map[T]bool
}

When I try to create a set of reflect.Type the following error is raised: "reflect.Type does not implement comparable".

I would understand this error, since reflect.Type is an interface; However, I know that using reflect.Type as the key of a map is explicitly allowed.

Is there any way to get around this problem other than changing the implementation of the set?

Ido Winter
  • 11
  • 1
  • in Go 1.18 interfaces don't implement `comparable` (the constraint) but *are comparable* (as defined in the language specs), so as you already found out, you can use them as map keys directly but can't instantiate type params constrained by `comparable` – blackgreen Jun 14 '22 at 06:41
  • This quirk of the Go 1.18 implementation is currently being (heatedly) discussed in the Go issue tracker, and one of the main use cases for this to work is precisely `reflect.Type` as map key, so there's good chances that at some point in the future this contradiction will be resolved; but as of today, you're stuck with this – blackgreen Jun 14 '22 at 06:43
  • soon: [proposal: spec: allow basic interface types to instantiate comparable type parameters](https://github.com/golang/go/issues/56548) – blackgreen Nov 16 '22 at 19:49

0 Answers0