Skip to the workspace
Pebellslearn by building
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.

golang / Maps

Explore each scene at your own pace.

01 · The rule

The rule

Maps

A 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.

Insert, read and delete entries while accounting for missing keys and nil 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.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.