Skip to content
Tutorials Center
My learning

Topics

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.

Go
for k := range maps.Keys(m) {
	fmt.Println(k)
}
keys := slices.Sorted(maps.Keys(m))

Try it

Go Sorted keys and collected values

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.

Go Stopping early and counting

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

Go
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), or slices.SortedFunc with a comparison function.
  • Plain range is still fine. for k := range m does the same job without the package; use maps.Keys when you want to pass a sequence to another function.
  • No copy is made. The iterator reads the live map. Collect it first with slices.Collect if 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, and slices.Max(slices.Collect(maps.Values(m))) finds the largest one.
  • Before Go 1.23 maps.Keys returned a slice from the experimental golang.org/x/exp/maps package. Code written for that version needs a small change.
  • break is safe. The iterator receives false from yield and returns right away.