Generic key in map


I want to make a generic struct that wraps a map.

package main

type MyMap[K comparable, V any] struct{
    internalMap map[K]V

This works fine but when I want to use MyMap with the key reflect.Type I get a compiler error.

reflect.Type does not implement comp arable

But I can use reflect.Type as key in a map. What is the correct interface that K must implement?

I think you are stuck. reflect.Type is an interface. The concrete type of the values returned by reflect.TypeOf are *reflect.rtype. Really want to use *reflect.rtype for your key type, but it’s inaccessible. The compiler requires the generic key type used in a map to implement comparable. Interface types do not: builtin package - builtin - Maybe you can hack around it with a uintptr from the pointer underlying reflect.Type. The builtin map doesn’t seem to have the same requirement for comparable keys.

Some experimentation here: Go Playground - The Go Programming Language

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.