Go 1.27 reference · Slices, Maps, Iterators and JSON
Go maps.Keys and slices.Sorted Function
Iterate a map's keys or values; combine with slices.Sorted for a deterministic order, since map iteration is random.
Go 1.27 Since 1.23
Syntax
func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] func Sorted[E cmp.Ordered](seq iter.Seq[E]) []E
Parameters
| Parameter | Description |
|---|---|
maps.Keys / maps.Values |
Iterators over keys / values. |
slices.Sorted / slices.Collect |
Turn an iterator into a slice. |
maps.Clone / maps.Copy |
Copy maps. |
Examples
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
stock := map[string]int{"tea": 3, "mug": 9, "kettle": 1}
for _, name := range slices.Sorted(maps.Keys(stock)) {
fmt.Println(name, stock[name])
}
}
Output
kettle 1 mug 9 tea 3
Run this on your computer — see “Get Started” for setup.
package main
import (
"fmt"
"maps"
)
func main() {
a := map[string]int{"x": 1}
b := maps.Clone(a)
b["y"] = 2
fmt.Println(len(a), len(b))
total := 0
for v := range maps.Values(b) {
total += v
}
fmt.Println(total)
}
Output
1 2 3
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Go 1.23 | Added |
Related
slices.Sort and slices.SortFunc· Sort a slice in place in ascending order, or with a comparison function for custom and multi-key ordering.iter.Seq (range over functions)· Write iterators as functions that yield values, and loop over them with for range like slices and maps.- Go Maps · tutorial