Go 1.18
It is now possible to write a generic function to extract all key-value pairs, i.e. the map entries, with any key and value types.
Notes:
- the map iterations are still unordered — using generics doesn't change that.
- the constraint for the map key must be comparable
type Pair[K, V any] struct {
First K
Second V
}
func Entries[M ~map[K]V, K comparable, V any](m M) []Pair[K, V] {
entries := make([]Pair[K, V], 0)
for k, v := range m {
entries = append(entries, Pair[K, V]{k, v})
}
return entries
}
The type Pair
here is used to preserve type safety in the return value. If you really must return a slice of slices, then it can only be [][]any
(or [][2]any
) in order to hold different types.
If the map key and value have the same type, of course you can still use Pair
but you can also use a type-safe variation of the above:
func Entries[T comparable](m map[T]T) [][2]T {
entries := make([][2]T, 0)
for k, v := range m {
entries = append(entries, [2]T{k, v})
}
return entries
}
Again, T
must be comparable
or stricter in order to work as a map key.
Playground: https://go.dev/play/p/RwCGmp7MHKW