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 8 hands-on exercises. Estimated time: 18 minutes.
- What is a map — A map lets you look up a key (like an ISBN) and get its value (like a book title). Run this to look up two books by ISBN…
- Declare with make — `make(map[string]int)` creates an empty map. Add two ISBNs with copy counts (3 and 5) and print the map.
- Add and update — Adding and updating use the same syntax: `copies["ISBN"] = N`. Add a new book with 6 copies, then update an existing one…
- Read a value and check if it exists 🤯 — Reading a missing key returns zero — silently. But `count, ok := copies["ISBN"]` tells you if it truly exists (ok=true) …
- Delete a key — `delete(map, key)` removes a key-value pair. Delete two books from the catalog and print the result.
- Loop over a map — `for isbn, count := range catalog` iterates every entry. Important: maps are unordered — the order may change each run. …
- Map with slice values — A map's value can be a slice: `map[string][]string` maps a member ID to their checked-out books. Add member M003 with tw…
- Build a genre counter — Loop through a genres slice and count each genre. `genreCounts[genre]++` works because Go returns 0 for missing keys. Ad…
Go Maps concepts covered
- Look things up by name