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
| Operation | nil map | Empty map from make |
|---|---|---|
len(m) | 0 | 0 |
m[k] read | Zero value | Zero value |
v, ok := m[k] | Zero, false | Zero, false |
m[k] = v | Panic | Works |
delete(m, k) | No-op | Works |
for range m | Zero iterations | Zero iterations |
m == nil | true | false |
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 type | Legal? |
|---|---|
string, all numeric types, bool, rune | Yes |
| Pointers, channels | Yes, compares identity |
| Structs and arrays of comparable fields | Yes |
[]byte, slices, maps, functions | No |
any / interface | Compiles, but panics at run time if the dynamic value is uncomparable |
| Floats | Legal, 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 want | What to write |
|---|---|
| Increment a counter | m[k]++ works, because it is a read, add, write |
| Set one field of a struct value | Read into a variable, set the field, write back |
| Mutate in place, repeatedly | Make the value a pointer: map[string]*Summary |
| Append to a slice value | m[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 get | Do |
|---|---|
| Sorted keys, modern | slices.Sorted(maps.Keys(m)) |
| Sorted keys, any version | Collect into a slice with append, then sort.Strings |
| Insertion order | Keep a separate []K alongside the map |
| Any single entry | Range 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
| Pattern | Result |
|---|---|
| Many goroutines reading, none writing | Safe |
| One writing while any other reads or writes | fatal error: concurrent map writes |
Guarded by sync.RWMutex | Safe |
sync.Map | Safe, 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
| Function | Does |
|---|---|
maps.Clone | Shallow copy; values that are pointers or slices remain shared |
maps.Equal, maps.EqualFunc | Compare, since == on maps is illegal |
maps.Copy(dst, src) | Merge src into dst |
maps.DeleteFunc | Delete every entry matching a predicate |
maps.Keys, maps.Values | Iterators, 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.
| Form | Cost per entry | Reads as |
|---|---|---|
map[string]struct{} | Key only; the value occupies zero bytes | _, ok := set[k] |
map[string]bool | Key plus one byte | if 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
- Writing to a nil map. Reads are fine, writes panic with
assignment to entry in nil map. Initialize map fields in a constructor.
- Using a single-value read to test presence.
if m[k] != 0cannot distinguish a stored zero from a missing key. Usev, ok := m[k].
- Trying
m[k].Field = von a struct value. Map elements are not addressable. Read, modify, write back, or store pointers.
- Forgetting the write-back.
s := m[k]; s.Count++with nom[k] = ssilently does nothing.
- Depending on iteration order. It is randomized on every run by design. Sort the keys.
- Reading and writing a map from several goroutines. The result is
fatal error: concurrent map writes, whichrecovercannot catch. Guard it or usesync.Map.
- Using a
[]byteas a key. Slices are uncomparable. Convert withstring(b); the lookup form is optimized not to allocate.
- Using
anykeys carelessly. It compiles, then panics at run time the first time somebody inserts a slice.
- Expecting a map to release memory after
deleteorclear. The buckets stay. Rebuild the map if the high-water mark was much larger than the steady state.
- Comparing maps with
==. Illegal except againstnil. Usemaps.Equal.
- Assuming
maps.Clonegives 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]++andm[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
- 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.
- 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 withmap[string]*Summary.
- 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.
- Set Two Ways: Implement deduplication of at least eight IDs with
map[string]struct{}and again withmap[string]bool. Compare the insertion and lookup lines side by side, then measurelenof both and say which you would use in a shared codebase and why.