Introduction
A slice finds items by their position, but often you want to find something by a name: the price of an apple, the number of times a word appears, the phone number of a person. A map does this. It stores key and value pairs and finds a value from its key very quickly, no matter how many pairs there are. Maps are one of the most useful tools in Go, and counting things with a map is a pattern you will use again and again.
How it works
The type of a map is written map[KeyType]ValueType. For example map[string]int has text keys and whole-number values. Make an empty map with make, or write one with a literal:
stock := make(map[string]int)
prices := map[string]float64{"apple": 0.5, "pear": 0.75}
Add or change a pair with m[key] = value, and read a value with m[key]. Every key appears only once; setting it again replaces the old value. len(m) is the number of pairs, and delete(m, key) removes a pair.
What happens if you read a key that is not there? You get the zero value of the value type: 0 for ints. That is useful for counting, because count[word]++ works even for a word you have not seen: the missing value counts as 0 and becomes 1. But it also hides a problem: you cannot tell a stored 0 from a missing key. For this, use the comma ok form:
v, ok := stock["apple"]
ok is true when the key exists. Writing to a nil map, one that was declared with var m map[string]int and never made, stops the program, so always create a map with make or a literal before you write to it.
Iterating a map with range gives the key and the value of each pair, but the order is random and can change from run to run. If your output must be in a fixed order, collect the keys into a slice, sort it, and then read the values in that order:
keys := []string{}
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
Values can be anything, for example a slice: map[string][]string groups items under a key, and you add to a group with groups[key] = append(groups[key], item). Keys must be types that can be compared with ==, such as strings, numbers and bools; a slice cannot be a key.
Example
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
stock := make(map[string]int)
stock["apple"] = 5
stock["pear"] = 2
stock["apple"] += 3
v, ok := stock["kiwi"]
fmt.Println(stock["apple"], v, ok)
delete(stock, "pear")
fmt.Println(len(stock))
count := make(map[string]int)
for _, w := range strings.Fields("go is fun and go is fast") {
count[w]++
}
keys := []string{}
for k := range count {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, count[k])
}
groups := map[string][]string{}
for _, w := range []string{"apple", "avocado", "banana", "blueberry", "cherry"} {
first := w[:1]
groups[first] = append(groups[first], w)
}
fmt.Println(groups["a"], groups["b"], len(groups["z"]))
}Line by line
stockis made withmake; the next lines add and change pairs.v, ok := stock["kiwi"]shows the comma ok form: kiwi is missing, sookis false andvis 0.delete(stock, "pear")removes a pair, andlencounts the rest.- The word count uses
count[w]++in a loop overstrings.Fields; no check for new words is needed. - The keys are copied into a slice and sorted with
sort.Strings, so the report is always in the same order. groupsis a map of slices: each word is added to the group for its first letter.
Expected result
8 0 false
1
and 1
fast 1
fun 1
go 2
is 2
[apple avocado] [banana blueberry] 0
In the real world
Maps are behind caches, indexes, counters and lookups of every kind: the number of visits per page, the user for each session id, the stock of each product. Go maps are fast, with a lookup time that hardly depends on their size. When you need to show results to a person or to compare output, you must sort the keys first, because a random order would make the output different each time.
Common mistakes
- Printing a map with range and expecting the same order every time. It is random.
- Writing to a nil map, which stops the program. Use
make. - Reading a missing key and treating the 0 as real data. Use comma ok when it matters.
- Using a slice as a key. Keys must be comparable.
- Changing a map while sorting its keys by accident; copy the keys first.
Best practices
- Create maps with
makeor a literal, never use a nil map for writing. - Use
count[key]++for counting, and comma ok when absence has a meaning. - Sort the keys whenever the output order matters.
Summary
A map stores key and value pairs and finds a value by its key. A missing key gives the zero value, and the comma ok form tells you whether the key exists. delete removes a pair, a map must be made before it is written to, and since the iteration order is random, you sort the keys to print in a fixed order.
Quick check
Key takeaways
- A map looks up a value by key, very quickly: m[key] = value and v := m[key].
- A missing key gives the zero value; use v, ok := m[key] to find out if it exists.
- The order of a map is random: collect the keys, sort them and then print.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.