Maps: Look It Up

Store pairs of keys and values

9 min read

A slice is great when position matters: first, second, third. But often you want to look something up by name: what is the capital of France, what score does this player have? For that, Go gives you the map.

Making a map

scores := map[string]int{
    "mia":  12,
    "raj":  9,
    "lena": 15,
}

map[string]int reads as: a map from string keys to int values. Each entry is a key: value pair. Think of it as a tiny two-column table where the left column must be unique.

Reading and writing entries

fmt.Println(scores["mia"])

scores["raj"] = 11
scores["kai"] = 3

delete(scores, "lena")

Reading uses the key in square brackets and prints 12. Assigning to a key updates it if it exists or creates it if it does not, so after these lines raj has 11 and kai is a brand new entry. The built-in delete removes an entry completely.

The comma-ok trick

What happens if you read a key that is not there? Go quietly gives you the zero value, so scores["zoe"] returns 0. But is that a real score of 0, or a missing player? Go has a lovely idiom to tell the difference:

score, ok := scores["zoe"]

if ok {
    fmt.Println("zoe scored", score)
} else {
    fmt.Println("zoe has not played yet")
}

Reading with two variables gives you the value and a bool named ok by tradition, which is true only if the key really exists. This comma-ok pattern shows up all over Go.

Looping over a map

for name, score := range scores {
    fmt.Println(name, "has", score, "points")
}

range hands you each key and value in turn. One famous quirk: Go visits map entries in random order, on purpose, so programmers never accidentally rely on an ordering that was never promised.

Choosing between a slice and a map is easy: if order and position matter, use a slice. If you look things up by a name or id, use a map.

Quick check

Q1 In value, ok := scores["zoe"], what does ok tell you?

Q2 In what order does range visit the entries of a map?

Want to save your progress? It's free.

Create a free account