Re:The Next Step for Generics
by rowanseymour on Tuesday June 16, 2020 @04:28PM
(#23543657)
The only time I get frustrated by the lack of generics in go in trying to get keys from a map... I can't have a single `keys(map[string]T) []string` function.
[ Parent
| on HN ]
I started to write one in the "Go 2 playground", but then realized they had that exact example in the draft design:
func Keys(type K comparable, V interface{})(m map[K]V) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
Usage: m := map[int]int{1:2, 2:4}
k := maps.Keys(m)
// Now k is either []int{1, 2} or []int{2, 1}.Well, you can :) https://play.golang.org/p/sum21uSy1Ae
For certain values of can.
Never said it was a good idea. It's inefficient, unsafe and hard to read but, as far as I can tell any generic function with concrete return types can be written using reflect (and any generic function with generic return types can be written also, it just requires the caller to manually cast from an interface{} to the correct type).
So, that's an interesting thing.