Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Maps & Structs  ›  Lesson

Maps

Maps 14 minA map stores values by key, returns the zero value for a missing key, must be created before it is written to, and is iterated in an unspecified order.

Maps

This is the lesson tally has been waiting for. Counting words means looking up a word and bumping its number, thousands of times. A map does that lookup in constant time, and Go's zero values make the counting line almost too short to believe.

The rule

Missing keys read as zero; make before you write; order is never promised.

A map type is written map[KeyType]ValueType. Create one with make or a literal:

counts := make(map[string]int)
stops := map[string]bool{"the": true, "a": true}

The core operations:

counts["go"] = 3          // set
n := counts["go"]         // get: 3
delete(counts, "go")      // remove (no error if absent)
fmt.Println(len(counts))  // number of keys

Missing keys read as zero. Looking up a key that is not there returns the value type's zero value, with no error. That is what makes counting one line:

for _, w := range strings.Fields("the cat saw the dog") {
	counts[w]++
}
// map[cat:1 dog:1 saw:1 the:2]

Make before you write. A nil map (declared with var counts map[string]int) reads fine but panics on the first write.

Order is never promised. for w, n := range counts visits every pair, but the order is unspecified and Go shuffles it between runs on purpose. For stable output, sort the keys:

for _, w := range slices.Sorted(maps.Keys(counts)) {
	fmt.Println(w, counts[w])
}

Two more rules:

  • Keys must be comparable with ==: strings, numbers, booleans, arrays and structs of those work; slices, maps and functions do not.
  • Maps are shared, not copied. Assigning a map or passing it to a function hands over a reference to the same data, so a function can add to the caller's map.

The shortcut

For every map line, run three checks: made? missing key → zero? need an order → sort keys?

Counting "the cat saw the dog"Step 1 of 5
  1. Made?

    counts := make(map[string]int) — writable. Good.

Drills

Answer fast — trust the rule.

quick drill

counts := map[string]int{}. What is counts["zebra"]?

quick drill

After counting the words of "go go go stop", what is len(counts)?

quick drill

Which of these is not a valid map key type?

quick drill

A function addWord(m map[string]int) sets m["new"] = 1. Does the caller's map see it?

quick drill

You print a map with for k, v := range m twice in one run. What can you rely on?

Remember

  • Missing keys read as zero; make before you write; order is never promised.
  • Shortcut: made? missing → zero? need an order → sort keys.
  • Trap: nil maps panic on write, and range order changes between runs.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe heart of tally

Explain how tally counts words with a map: how the map is created, why counts[w]++ works even for a word seen for the first time, and why printing for w, n := range counts gives a different order on different runs. Say how you would print the words alphabetically.