Maps: Fast Lookups

Maps: Fast Lookups in Go: Behind the counter of a busy pharmacy is a rack of pigeonholes, and every made-up prescription bag goes into one of them.

The Analogy: The Pharmacy's Prescription Rack

Behind the counter of a busy pharmacy is a rack of pigeonholes, and every made-up prescription bag goes into one of them. What makes the rack fast is not that it is tidy but that the pharmacist never searches it. She takes the customer's surname, computes from the name alone which pigeonhole it must be in, and looks only there. Ten bags or ten thousand, the work is the same: one calculation, one look. That calculation is a hash, and it is the entire reason a map answers "do you have this?" in constant time while a slice has to walk from one end.

The rack is bolted to the wall, and this is the property that separates maps from arrays and slices in Go. When you tell a colleague "use the rack", you have not handed them a copy of the rack; you have pointed at it. Both of you file into the same pigeonholes and both of you see each other's bags. A Go map value is a small handle onto a hash table living elsewhere, so assigning a map to another variable, or passing it to a function, gives both names access to the same table. A function that adds an entry to a map parameter has changed the caller's map, with no pointer and no return value in sight.

Now the awkward case. A rack that was never installed is not the same as an empty rack. You can still walk up to the wall and ask whether a bag for Patel is there, and the answer is a perfectly sensible no. But try to file a bag and there is nowhere to put it, and in Go that is not a polite error, it is a panic: assignment to entry in nil map. A nil map reads like an empty one and writes like a brick wall. Knowing that asymmetry is what stops the most common map crash in the language.

Finally, the pharmacist deliberately starts at a different pigeonhole every time she walks the whole rack. That sounds perverse until you understand why Go does it: the iteration order of a map is randomized on purpose, on every single run, so that nobody can write code, or a test, that quietly depends on an order the implementation never promised. If you want an order, you have to say which one, and the ritual for that appears in the example at the end of this lesson.


Syntax or Core Structure

Declaration, the comma-ok read, writes, delete, and the proof that a map is a handle rather than a copy.

package main

import "fmt"

func main() {
    var nilMap map[string]int
    stock := map[string]int{"aspirin": 120, "ibuprofen": 0}
    sized := make(map[string]int, 64) // 64 is a hint, not a limit

    fmt.Println("nilMap len:", len(nilMap), "isNil:", nilMap == nil)
    fmt.Println("read from nil map:", nilMap["anything"])

    // The comma-ok form is the only way to tell zero from missing.
    v1, ok1 := stock["ibuprofen"]
    v2, ok2 := stock["codeine"]
    fmt.Printf("ibuprofen=%d present=%t\n", v1, ok1)
    fmt.Printf("codeine=%d   present=%t\n", v2, ok2)

    stock["codeine"] = 5
    stock["aspirin"] += 30
    delete(stock, "ibuprofen")
    delete(stock, "never-stocked") // missing key: no panic, no effect

    fmt.Println("len after edits:", len(stock))

    // A map is a handle. Both names refer to one table.
    alias := stock
    alias["aspirin"] = 1
    fmt.Println("read through the original:", stock["aspirin"])

    sized["paracetamol"] = 40
    fmt.Println("sized len:", len(sized))
}

Output:

nilMap len: 0 isNil: true
read from nil map: 0
ibuprofen=0 present=true
codeine=0   present=false
len after edits: 2
read through the original: 1
sized len: 1

Two lines carry most of the lesson. ibuprofen is present with the value zero and codeine is absent with the value zero, and a single-value read cannot tell them apart, which is why v, ok := m[k] exists. And alias["aspirin"] = 1 changed stock, because alias := stock copied a handle, not a table.

The one thing this program cannot demonstrate is the nil write, because it would stop the program:

var m map[string]int
m["key"] = 1 // panic: assignment to entry in nil map

A nil map is a perfectly good read-only empty map and a completely unusable writable one. Any map you intend to write to must come from make, a literal, or another map.


Technical Depth: A Handle, Not a Container

nil Versus Empty

Operationnil mapEmpty map from make
len(m)00
m[k] readZero valueZero value
v, ok := m[k]Zero, falseZero, false
m[k] = vPanicWorks
delete(m, k)No-opWorks
for range mZero iterationsZero iterations
m == niltruefalse

The practical rule: a nil map is a fine zero value for a read-only lookup table, and a fine thing to return from a function that found nothing, but a function that stores into a map field must initialize it first. This is the most common cause of a nil map panic: a struct with a map field that somebody constructed with &Thing{} instead of a constructor.

Key Types

Map keys must be comparable, which is the same rule as ==.

Key typeLegal?
string, all numeric types, bool, runeYes
Pointers, channelsYes, compares identity
Structs and arrays of comparable fieldsYes
[]byte, slices, maps, functionsNo
any / interfaceCompiles, but panics at run time if the dynamic value is uncomparable
FloatsLegal, but NaN never equals itself, so a NaN key is unretrievable

[]byte keys are the common frustration. The fix is string(b), and the compiler special-cases m[string(b)] so that no allocation happens for the lookup itself.

You Cannot Address a Map Element

&m[k] does not compile, and neither does m[k].Field = v when the value type is a struct. This is not an arbitrary restriction: the table moves entries when it grows, so a pointer into it would not stay valid.

What you wantWhat to write
Increment a counterm[k]++ works, because it is a read, add, write
Set one field of a struct valueRead into a variable, set the field, write back
Mutate in place, repeatedlyMake the value a pointer: map[string]*Summary
Append to a slice valuem[k] = append(m[k], v)

The counter and append forms are so common that they look like exceptions, but they are just read-modify-write spelled compactly. Anything involving a field of a struct value needs the three-line dance or a pointer value type.

Iteration Order Is Randomized on Purpose

Ranging a map visits every entry exactly once, in an order chosen fresh on every run of the program. This is not "unspecified but stable in practice"; the runtime picks a random starting bucket deliberately so that order-dependent code fails early and visibly rather than in production two years later.

To getDo
Sorted keys, modernslices.Sorted(maps.Keys(m))
Sorted keys, any versionCollect into a slice with append, then sort.Strings
Insertion orderKeep a separate []K alongside the map
Any single entryRange and break, accepting that it is arbitrary

Deleting during iteration is explicitly allowed: an entry deleted before it is reached will not be produced. Adding during iteration is allowed too, but a newly added entry may or may not be visited, so a loop that inserts while ranging is a loop whose behavior you cannot predict.

Maps Are Not Safe for Concurrent Use

PatternResult
Many goroutines reading, none writingSafe
One writing while any other reads or writesfatal error: concurrent map writes
Guarded by sync.RWMutexSafe
sync.MapSafe, tuned for keys written once and read often

That fatal error is worth calling out precisely: it is not a panic. The runtime detects the corruption and kills the process, and no recover will save you. The detection is also best-effort, so a data race on a map may equally produce a wrong answer or a segmentation fault instead. Run go test -race and believe what it tells you.

Sizing, and the Fact That Maps Never Shrink

There is no cap for a map. make(map[K]V, hint) preallocates space for roughly hint entries, which avoids rehashing while a large map is built and is worth doing whenever you know the rough size. Deleting entries, on the other hand, does not give memory back: the bucket array stays as large as the map's high-water mark for the lifetime of the map. A long-lived cache that once held a million entries still owns that space after you delete them all, and the only remedy is to build a fresh map and drop the old one. The clear(m) builtin, added in Go 1.21, deletes every entry but also keeps the buckets, so it is a convenience rather than a cure.

The maps Package

FunctionDoes
maps.CloneShallow copy; values that are pointers or slices remain shared
maps.Equal, maps.EqualFuncCompare, since == on maps is illegal
maps.Copy(dst, src)Merge src into dst
maps.DeleteFuncDelete every entry matching a predicate
maps.Keys, maps.ValuesIterators, since Go 1.23; feed them to slices.Sorted or slices.Collect

Sets

Go has no set type, so a map with a throwaway value type is the set.

FormCost per entryReads as
map[string]struct{}Key only; the value occupies zero bytes_, ok := set[k]
map[string]boolKey plus one byteif set[k]

map[string]bool wins on readability because a missing key reads as false with no comma-ok, and one byte per entry rarely matters. Use struct{} when the set is genuinely large or when you want the type to say "there is no value here". The insertion syntax set[k] = struct{}{} is the price.


Real World Example: Deduplicating and Grouping an Order Feed

Every idea in this lesson shows up in this one function: a set for deduplication, the zero value saving an initialization branch, the read-modify-write dance because map elements are not addressable, and the sort ritual that makes the report reproducible.

package main

import (
    "fmt"
    "sort"
)

type Order struct {
    ID     string
    Region string
    Cents  int
}

var feed = []Order{
    {"o-1", "gb", 1999},
    {"o-2", "de", 2500},
    {"o-1", "gb", 1999}, // redelivered
    {"o-3", "gb", 500},
    {"o-4", "fr", 7250},
    {"o-2", "de", 2500}, // redelivered
    {"o-5", "de", 100},
}

type Summary struct {
    Count int
    Cents int
}
func summarize(orders []Order) (map[string]Summary, int) {
    seen := make(map[string]struct{}, len(orders))
    byRegion := make(map[string]Summary)
    dropped := 0

    for _, o := range orders {
        if _, dup := seen[o.ID]; dup {
            dropped++
            continue
        }
        seen[o.ID] = struct{}{}

        s := byRegion[o.Region] // zero value on first sight of a region
        s.Count++
        s.Cents += o.Cents
        byRegion[o.Region] = s // write back: map elements are not addressable
    }

    return byRegion, dropped
}

func main() {
    byRegion, dropped := summarize(feed)

    regions := make([]string, 0, len(byRegion))
    for r := range byRegion {
        regions = append(regions, r)
    }
    sort.Strings(regions)

    total := 0
    for _, r := range regions {
        s := byRegion[r]
        fmt.Printf("%-3s orders=%d cents=%5d\n", r, s.Count, s.Cents)
        total += s.Cents
    }

    fmt.Printf("regions=%d dropped=%d total=%d\n", len(byRegion), dropped, total)
}

Output:

de  orders=2 cents= 2600
fr  orders=1 cents= 7250
gb  orders=2 cents= 2499
regions=3 dropped=2 total=12349

The three lines around s are the part worth staring at. byRegion[o.Region].Count++ would be the obvious thing to write and it does not compile, because a map element is not addressable: the table relocates entries when it grows, so there is no stable address to increment through. So you read the value out, modify your local copy, and write it back. Forget the write-back and the function compiles, runs, and reports every region as having zero orders, which is a genuinely nasty bug because the shape of the code looks right. If a value is going to be mutated repeatedly, declare the map as map[string]*Summary instead, and then byRegion[r].Count++ works because you are following a pointer rather than addressing a map slot.

There is no "if this region is new, create an entry" branch anywhere, and there does not need to be. Reading a missing key hands you the zero Summary, whose Count and Cents are already 0, so the first order for a region and the fiftieth take exactly the same path. This is the single most pleasant thing about Go maps, and it is what makes counts[word]++ and groups[k] = append(groups[k], v) work with no setup: both are reading a usable zero value out of a key that does not exist yet.

seen is a set, and make(map[string]struct{}, len(orders)) sizes it for the worst case so the table never rehashes while the feed is processed. struct{} occupies zero bytes, so the set costs keys only; the price is the struct{}{} composite literal, which every Go programmer has typed wrong at least once. Writing map[string]bool instead would let the duplicate test read if seen[o.ID] with no comma-ok at all, at a cost of one byte per order, and on a feed of this size that is the better trade. Both are correct; pick one per codebase and stop thinking about it.

Everything about the result is deterministic and nothing about the map is. Run this program a hundred times and for r := range byRegion yields de, fr and gb in a hundred different orders, which is exactly why the keys are collected into a slice and sorted before anything is printed. On Go 1.23 or later the whole ritual collapses to for _, r := range slices.Sorted(maps.Keys(byRegion)). Skip the sort and you get a report whose lines shuffle between runs, which breaks diffing, breaks golden-file tests, and eventually convinces somebody that the totals are wrong.


Common Mistakes

  1. Writing to a nil map. Reads are fine, writes panic with assignment to entry in nil map. Initialize map fields in a constructor.
  1. Using a single-value read to test presence. if m[k] != 0 cannot distinguish a stored zero from a missing key. Use v, ok := m[k].
  1. Trying m[k].Field = v on a struct value. Map elements are not addressable. Read, modify, write back, or store pointers.
  1. Forgetting the write-back. s := m[k]; s.Count++ with no m[k] = s silently does nothing.
  1. Depending on iteration order. It is randomized on every run by design. Sort the keys.
  1. Reading and writing a map from several goroutines. The result is fatal error: concurrent map writes, which recover cannot catch. Guard it or use sync.Map.
  1. Using a []byte as a key. Slices are uncomparable. Convert with string(b); the lookup form is optimized not to allocate.
  1. Using any keys carelessly. It compiles, then panics at run time the first time somebody inserts a slice.
  1. Expecting a map to release memory after delete or clear. The buckets stay. Rebuild the map if the high-water mark was much larger than the steady state.
  1. Comparing maps with ==. Illegal except against nil. Use maps.Equal.
  1. Assuming maps.Clone gives you an independent copy. It is shallow; slice and pointer values are still shared.

Best Practices

  • Use v, ok := m[k] whenever a stored zero value is meaningful, and the one-value form when it is not.
  • Lean on the zero value: m[k]++ and m[k] = append(m[k], v) need no presence check.
  • Size the map with make(map[K]V, n) when you know roughly how many entries are coming.
  • Store pointers as values when entries are mutated repeatedly, and structs when they are replaced wholesale.
  • Collect and sort keys before producing any output, or use slices.Sorted(maps.Keys(m)).
  • Initialize every map field in a constructor so no caller can reach a nil map write.
  • Guard shared maps with a sync.RWMutex, and run the test suite with -race.
  • Return a nil map for "nothing found" and let callers use len, rather than inventing a distinction between nil and empty.

Practice Exercises

  1. Zero Versus Missing: Build a map with a key whose value is genuinely 0. Write two presence checks, one with the single-value read and one with comma-ok, and show a case where they disagree. Then do the same on a nil map and record what each returns.
  1. The Silent No-Op: Write a grouping function that does s := m[k]; s.Count++ and forgets the write-back. Print the result and explain why it is empty rather than being a compile error. Fix it twice, once with the write-back and once with map[string]*Summary.
  1. Make It Reproducible: Print a ten-entry map by ranging it directly and run the program five times. Record whether the order changed. Then sort the keys, run five more times, and diff the outputs.
  1. Set Two Ways: Implement deduplication of at least eight IDs with map[string]struct{} and again with map[string]bool. Compare the insertion and lookup lines side by side, then measure len of both and say which you would use in a shared codebase and why.