Go Tutorial: Maps
Store and look up data by name, not by position. The key-value pair is one of the most useful data structures in programming.
Look things up by name
Slices and arrays are great when order matters — item 0, item 1, item 2.
But what if you want to look something up by name? You do not want "the third element." You want "the score for Alex."
That is what a map does. You give it a key, it gives you the value. Like a real dictionary — look up the word, get the definition.
Twelve steps.
What you'll learn in this Go maps tutorial
This interactive Go tutorial has 12 hands-on exercises. Estimated time: 18 minutes.
- What is a map — Think about a physical dictionary.
- Declare a map with make — When you want an empty map to fill later, use `make`.
- Declare with values — When you already have the data, declare and fill in one shot.
- Add and update a key — Adding a new key and updating an existing key use the exact same syntax.
- Read a value — Reading from a map returns the value — or the zero value if the key does not exist.
- Check if a key exists — The two-value assignment solves the ambiguity from the last step.
- Delete a key — `delete(map, key)` removes a key-value pair entirely.
- len on a map — `len(map)` returns how many key-value pairs are in the map.
- Loop over a map — `for key, val := range myMap` iterates over every key-value pair.
- Map with slice values — A map's value can be any type — including a slice.
- Nested maps — A map can also hold other maps.
- Build a word counter — Classic map use case: count how many times each word appears.
Go Maps concepts covered
- Look things up by name