3 ms·
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.
by rowanseymour 6y ago
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.
- vlads_ 6y agoWell, you can :) https://play.golang.org/p/sum21uSy1Ae https://play.golang.org/p/sum21uSy1Ae
- srathi 6y agoThis is an awesome use of the reflect package!
- grey-area 6y agoFor certain values of can.
- vlads_ 6y agoNever 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.
- benhoyt 6y agoI 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}.