Use maps and iter helpers
Use maps and iter helpers
The maps package supplies typed map helpers such as Clone and Equal (Go 1.21). Go 1.23 adds iterator helpers: maps.Keys produces an iter.Seq of keys, maps.All produces key-value pairs, and maps.Collect builds a map from a sequence. Iteration order for maps is unspecified; sort keys when producing deterministic reports.
package main
import ( "fmt" "maps" "slices")
func main() { a := map[string]int{"pen": 3, "book": 2} b := maps.Clone(a) b["pen"] = 7 fmt.Println(a["pen"], b["pen"], maps.Equal(a, b)) for _, k := range slices.Sorted(maps.Keys(a)) { fmt.Println(k, a[k]) }}Clone creates a separate map for a non-nil input, but copies keys and values shallowly. Equal compares values using == and requires comparable values. slices.Sorted consumes a sequence into a sorted slice. The iterator APIs and range-over-function require Go 1.23 or later.
Expected output:
3 7 falsebook 2pen 3Build a reusable sequence
package main
import ( "fmt" "iter" "slices")
func odds(n int) iter.Seq[int] { return func(yield func(int) bool) { for i := 1; i <= n; i += 2 { if !yield(i) { return } } }}func main() { for v := range odds(7) { fmt.Println(v) if v == 3 { break } } fmt.Println(slices.Collect(odds(5)))}An iter.Seq[T] is a function that accepts a yield callback. A range loop supplies that callback; false signals that the consumer stopped and the producer must stop calling yield. This sequence can be used again because its loop state is local to each call. Other iterators may be single-use; check their contract. Avoid changing a map concurrently during traversal without synchronization.
Expected output:
13[1 3 5]Try it locally
Clone map[string]int{"z":9,"a":1} with maps.Collect(maps.All(m)); print sorted keys and verify equality with maps.Equal.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Core library 05: Use maps and iter helpers
Check the lesson objective before moving on.
Why sort the result of maps.Keys for a report?
What must a producer do when yield returns false?