Maps

A map is a phone book: look something up by its key, get its value.

The idea

A phone book maps a name to a number. You never ask for “the third entry”; you ask for “Ada”. A Go map[string]int is the same: keys of one type, values of another, and lookups are fast no matter how big the book gets.

Two things surprise newcomers: asking for a missing key gives the zero value (not an error), so you use v, ok := m[k] to tell “missing” from “present but zero”; and the order of a loop over a map is deliberately random.

Watch it work

Try it

Common mistakes