Maps: lookup, comma-ok and iteration
A map is a hash table from keys to values. Both sides have a type, a key can be found in constant time, and the cost of that is the two rules this lesson is built on: a missing key reads as the zero value instead of an error, and the order of iteration is deliberately random. The previous lesson used an integer index; a map uses a key that can be compared.
make, literals and the comma-ok idiom
make(map[K]V) returns an empty map that is ready to write, map[K]V{...} is a literal, and delete removes a key. A read of a key that is not there returns the zero value of the value type, so a lookup needs the two-result form v, ok := m[k] to tell "absent" from "present and zero".
package main
import "fmt"
func main() {
ages := map[string]int{
"ada": 36,
"grace": 45,
}
fmt.Println("len:", len(ages))
ages["linus"] = 28
fmt.Println("linus:", ages["linus"])
fmt.Println("missing:", ages["nobody"], "len still:", len(ages))
age, ok := ages["grace"]
fmt.Println("grace:", age, "present:", ok)
_, ok = ages["nobody"]
fmt.Println("nobody present:", ok)
delete(ages, "ada")
fmt.Println("after the delete:", len(ages), ages["ada"])
}
go run basics.go
len: 2
linus: 28
missing: 0 len still: 3
grace: 45 present: true
nobody present: false
after the delete: 2 0
ages["nobody"] printed 0 and did not add a key, which is why the length stayed 3 after the read and fell to 2 after the delete. The errors lesson applied the same idea to a nil error: the value that is not there has a representable zero form, and ok is the question "was it there?".
Iteration order is random
for k, v := range m visits every pair once, in an order the runtime chooses, and it may choose a different one for every range statement in the same run. The language makes the order random on purpose, so that no program comes to depend on the layout of the hash table.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
names := []string{"go", "rust", "c", "zig", "java", "kotlin", "swift", "python",
"ruby", "perl", "php", "lua", "dart", "scala", "haskell", "elixir"}
scores := make(map[string]int, len(names))
for i, name := range names {
scores[name] = i
}
for range 3 {
first := make([]string, 0, 5)
for name := range scores {
first = append(first, name)
if len(first) == 5 {
break
}
}
fmt.Println("first five:", first)
}
for _, name := range slices.Sorted(maps.Keys(scores)) {
fmt.Printf("%s ", name)
}
fmt.Println()
}
go run order.go
first five: [rust swift python lua haskell]
first five: [zig java ruby scala elixir]
first five: [zig java ruby scala elixir]
c dart elixir go haskell java kotlin lua perl php python ruby rust scala swift zig
Each of the three passes started at a different key, and none of them followed the order in which the names were inserted. The runtime may choose another start for the next run or the next machine, so no program should depend on the sequence. A program that needs a fixed order sorts the keys. Since Go 1.23 maps.Keys returns an iterator and slices.Sorted collects it in order, which replaced the older sort.Strings(keys) dance. The sorting lesson covers the general case.
Counting and grouping
The zero value makes a counter one line long: counts[w]++ reads the missing key as 0, adds one and stores it, so no "if the key exists" branch is needed. Grouping values into slices works the same way, because append accepts a nil slice.
package main
import "fmt"
func main() {
words := []string{"go", "map", "go", "slice", "go"}
counts := make(map[string]int)
for _, w := range words {
counts[w]++
}
fmt.Println("counts:", counts)
byFirst := make(map[string][]string)
for _, w := range words {
prefix := w[:1]
byFirst[prefix] = append(byFirst[prefix], w)
}
fmt.Println("g words:", byFirst["g"])
fmt.Println("groups:", len(byFirst))
}
go run counter.go
counts: map[go:3 map:1 slice:1]
g words: [go go go]
groups: 3
fmt prints a map with its keys sorted, so the output of the first Println is stable even though a range over the same map is not. byFirst["g"] holds the three words that start with g, in the order they were appended, and the map has one entry per first letter.
The nil map
A declared map with no make is nil. Reading it is fine, deleting from it is fine and ranging over it does nothing, but writing to it panics, because there is no hash table to write into.
package main
import "fmt"
func main() {
var counts map[string]int
fmt.Println("read from nil:", counts["go"], "len:", len(counts))
counts["go"] = 1
fmt.Println(counts)
}
go build -trimpath -o nilmap nilmap.go
GOTRACEBACK=none ./nilmap 2>&1 | grep -v signal
./nilmap >/dev/null 2>&1; echo status: $?
read from nil: 0 len: 0
panic: assignment to entry in nil map
status: 2
The panic is assignment to entry in nil map and the process exits with status 2. A function that fills a map either calls make itself or documents that the caller must pass a live map. A nil slice, by contrast, accepts append: the difference is that a slice header can grow out of nothing and a map has no such zero form.
Keys must be comparable
A key type has to support ==, because the table finds a key by comparing hashes and then keys. Numbers, strings, booleans, pointers, channels, interfaces and structs and arrays of those are fine; a slice, a map or a function is not, and the compiler says so.
package main
import "fmt"
func main() {
groups := map[[]int]string{}
fmt.Println(groups)
}
go build -o badkey badkey.go 2>&1 | head -3
# command-line-arguments
./badkey.go:6:16: invalid map key type []int
The usual fix is a string key, such as strings.Join(parts, "/"), or a struct of comparable fields. An interface key compiles but panics at run time if a value stored in it is uncomparable, which is one more reason to keep keys concrete. The next lesson opens the table itself.
Exercises
- Count the words of a sentence in a map and print the three most frequent. Which step needs a slice?
- Store a map[string]map[string]int of city to month to temperature, and write a lookup that reports a missing city and a missing month differently.
- Build the set of the distinct words of a text with map[string]struct{}{}. Why is the empty struct a better value than bool here?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the zero value of a map?
Answer
nil, and a write to it panics
A declared map is nil; make is what creates the table that accepts writes.
-
What does
v, ok := m[k]give for a key that is not in the map?Answer
The zero value and false
The second result is the presence flag, and the first is the zero value of the value type.
-
What happens when a nil map is read?
Answer
It returns the zero value, as any missing key does
Reads, deletes and ranges work on a nil map; only a write needs the table.
-
What does this program print?
package main import "fmt" func main() { m := map[string]int{"a": 1} m["b"] = 2 fmt.Println(len(m), m["c"]) }Answer
2 0
The map holds two keys after the write, and the missing key reads as 0 without being added.
-
What does this program print?
package main import "fmt" func main() { words := []string{"go", "map", "go", "slice", "go"} counts := make(map[string]int) for _, w := range words { counts[w]++ } fmt.Println(counts["go"], len(counts)) }Answer
3 3
The word go appears three times, and the map has one entry per distinct word.
-
What does this program print?
package main import ( "fmt" "maps" "slices" ) func main() { m := map[string]int{"c": 3, "a": 1, "b": 2} fmt.Println(slices.Sorted(maps.Keys(m))) }Answer
[a b c]
Sorted collects the keys of the iterator in ascending order.
-
What does
delete(m, k)do when k is not in the map?Answer
Nothing, and it does not panic
delete is defined for every key, present or not, and returns nothing.
-
Which type can be a map key?
Answer
A struct of comparable fields
Keys need ==, so slices, maps and functions are out; a struct whose fields are comparable is in.
-
What happens when a nil map is written to?
Answer
A run-time panic: assignment to entry in nil map
There is no table behind a nil map, and the runtime stops the program.
-
Why is the iteration order of a map random?
Answer
So that no program depends on the hash table layout
The runtime deliberately varies the start of the range to expose code that assumes an order.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev