Maps
What you will learn
A map stores values that you look up by a key, such as a name, an ID, or a word. This lesson covers creating maps, reading and writing entries, telling a missing key from a zero value, deleting, iterating in a stable order, the nil-map panic, and the rules about concurrent use.
When to use a map
A slice finds an item by its position, so finding "Grace" means scanning the list. A map finds an item by its key directly, so the lookup takes about the same time no matter how many entries there are. Use a map whenever you think "look up this by that".
ages := map[string]int{
"Ada": 36,
"Grace": 40,
}
The type map[string]int means "keys are strings, values are integers". Each key appears at most once.
Create and update
You can start from a literal, or create an empty map with make:
scores := make(map[string]int)
scores["blue"] = 10 // adds the key
scores["red"] = 8
scores["blue"]++ // updates the existing key
Assigning to a key either adds it or replaces its value. The number of entries is len(scores).
Reading a value
score := scores["blue"]
fmt.Println(score) // 11
If the key does not exist, you get the zero value of the value type, 0 here, with no error. That causes an ambiguity: did the key not exist, or is its value actually zero?
The comma-ok form settles it. A lookup can return a second value saying whether the key was found:
score, ok := scores["green"]
if !ok {
fmt.Println("green has no score yet")
} else {
fmt.Println("green:", score)
}
This is used so often that you will see a short version: if score, ok := scores["green"]; ok { ... }.
Deleting
delete(scores, "red")
Deleting a key that is not there is safe and does nothing.
Iterating
for team, score := range scores {
fmt.Println(team, score)
}
The order of iteration is deliberately random and can change between runs. Never rely on it. If you need stable output, collect the keys into a slice, sort it, and read the map in that order:
keys := make([]string, 0, len(scores))
for key := range scores {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Println(key, scores[key])
}
Maps are shared, not copied
Assigning a map to another variable does not copy its entries. Both variables refer to the same map:
first := map[string]int{"a": 1}
second := first
second["a"] = 99
fmt.Println(first["a"]) // 99
The same applies when you pass a map to a function: the function can change the caller's map. To get an independent copy, use maps.Clone(first) from the standard library maps package, or build a new map and copy each pair.
Nil maps
A map you declare but never create is nil:
var users map[string]string
fmt.Println(users["42"]) // fine: prints an empty string
users["42"] = "Mira" // panic
panic: assignment to entry in nil map
Reading from, ranging over, and taking the len of a nil map are all safe. Writing is not. Create the map with make or a literal before you write to it.
Valid keys
A key type must support ==. Strings, numbers, booleans, pointers, arrays, and structs made only of comparable fields all work. Slices, maps, and functions do not, so map[[]int]string will not compile.
Maps of slices and structs
A map's values can be anything, including slices, which is handy for grouping:
groups := make(map[string][]string)
groups["fruit"] = append(groups["fruit"], "apple")
groups["fruit"] = append(groups["fruit"], "pear")
groups["veg"] = append(groups["veg"], "carrot")
Reading a missing key gives a nil slice, which append handles happily, so no setup is needed.
One restriction catches people out: you cannot change a field of a struct stored in a map directly.
type Player struct{ Score int }
players := map[string]Player{"ada": {Score: 1}}
players["ada"].Score = 10 // compile error
cannot assign to struct field players["ada"].Score in map
Read the value, change it, and store it back, or use a map of pointers (map[string]*Player).
Using a map as a set
Go has no built-in set type. The usual stand-in is a map with bool or empty-struct values:
seen := make(map[string]bool)
seen["go"] = true
if seen["go"] {
fmt.Println("already seen go")
}
map[string]struct{} uses no memory for the values, but bool is easier to read for most programs.
Concurrency warning
A map is not safe to read and write from several goroutines at the same time. Doing so can crash the program with fatal error: concurrent map writes. Either keep the map inside one goroutine, protect it with a mutex, or use a structure designed for sharing. The concurrency stage covers this properly.
Common mistakes
- Writing to a nil map. Always create it first.
- Relying on iteration order. Sort the keys when order matters.
- Using the zero value to detect absence. Use the comma-ok form.
- Expecting an assignment to copy the map.
- Trying to modify a struct field inside a map without storing the struct back.
Practice
Count how often each word appears in a sentence. Then print the words and their counts in alphabetical order. Use the sentence "go is fun go is fast go".
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
sentence := "go is fun go is fast go"
counts := make(map[string]int)
for _, word := range strings.Fields(sentence) {
counts[word]++
}
words := make([]string, 0, len(counts))
for word := range counts {
words = append(words, word)
}
sort.Strings(words)
for _, word := range words {
fmt.Println(word, counts[word])
}
}
Output:
fast 1
fun 1
go 3
is 2
strings.Fields splits the sentence into words. counts[word]++ works even the first time because a missing key reads as 0, which is then increased to 1. Map iteration order is random, so the keys are copied into a slice and sorted before printing.
Summary
A map looks values up by key, with the type written map[KeyType]ValueType. A missing key reads as the zero value, so use the comma-ok form when absence matters. Iteration order is unspecified, so sort the keys for stable output. Maps are shared when assigned, writing to a nil map panics, and ordinary maps are not safe for concurrent writes.
Official reference: Go maps in action.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.