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

Create a free account to save this page, take notes and track your progress. Sign in

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

ParameterDescription
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

Example 1
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.

Clone and sum values
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

VersionChange
Go 1.23Added

Was this page helpful?