Go Reference ยท Collections: sort, slices, maps
Go maps.Keys() and maps.Values() functions
Reference for Go maps.Keys, maps.Values and maps.All (Go 1.23): iterator functions over a map, how to sort keys, collect them into slices and stop early.
maps.Keys(m) returns an iterator over the keys of a map, and maps.Values(m) returns an iterator over its values. maps.All(m) yields both as key-value pairs. They were added in Go 1.23, together with range-over-function loops.
The functions do not allocate a slice. They return a sequence you can loop over with for ... range, or hand to a function such as slices.Collect or slices.Sorted to build a slice.
for k := range maps.Keys(m) { fmt.Println(k) } keys := slices.Sorted(maps.Keys(m))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] func Values[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[V] func All[Map ~map[K]V, K comparable, V any](m Map) iter.Seq2[K, V]
| Name | Description |
|---|---|
m |
The map to iterate. May be nil, which yields nothing. |
Returns: iter.Seq[K] or iter.Seq[V], a function of the form func(yield func(K) bool); All returns iter.Seq2[K, V].
Edge cases: nothing is evaluated until you start ranging. If the map changes while you iterate, the usual map rules apply: entries removed before they are reached are not produced, and entries added may or may not be seen.
Usage notes
- The order is random. Each loop may visit entries in a different order. For deterministic output use
slices.Sorted(maps.Keys(m)), which needs ordered keys (cmp.Ordered), orslices.SortedFuncwith a comparison function. - Plain
rangeis still fine.for k := range mdoes the same job without the package; usemaps.Keyswhen you want to pass a sequence to another function. - No copy is made. The iterator reads the live map. Collect it first with
slices.Collectif you plan to modify the map inside the loop in unusual ways. - Combine with other iterator helpers.
slices.Collect(maps.Values(m))gives a slice of values, andslices.Max(slices.Collect(maps.Values(m)))finds the largest one. - Before Go 1.23
maps.Keysreturned a slice from the experimentalgolang.org/x/exp/mapspackage. Code written for that version needs a small change. breakis safe. The iterator receivesfalsefromyieldand returns right away.