The maps Package
Start with The maps Package
The generic maps package helps clone, compare and iterate Go map collections.
What you’ll learn
- Explain the main purpose of the maps package.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
maps.Clone creates a shallow copy of the map entries; maps.Equal compares map key/value pairs when values are comparable. Map iteration order is unspecified, so sort keys before generating predictable output or displaying sorted results.
Go 1.23 added maps.Keys and related iterator helpers. A clone of a map containing slices or pointers shares referenced nested data unless you copy those values separately.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"maps"
)
func main() {
original := map[string]int{"apples": 2, "pears": 3}
copied := maps.Clone(original)
copied["apples"] = 5
fmt.Println("Original apples:", original["apples"])
fmt.Println("Copy apples:", copied["apples"])
fmt.Println("Equal:", maps.Equal(original, copied))
}
Output
Original apples: 2
Copy apples: 5
Equal: falseTrace what the program does
The copied map has independent entries, so updating copied["apples"] leaves original["apples"] equal to 2. The two maps no longer compare equal.
Avoid common mistakes
- Cloning does not recursively clone pointer or slice values stored in map entries.
- Do not rely on the order of range over a map.
Try it yourself
Add a new key to the cloned map and use maps.Equal to compare before and after the change.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced The maps Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.