Lesson 18 of 38 · Slices & Maps
Go Maps: Create, Read, Update, Delete and comma-ok
A slice finds things by position. Often you want to find them by name instead: the price of an item, the phone number of a guild member, how many times a word appears. That's the job of Go maps — Go's built-in hash tables, which store key → value pairs and find the value for a key in a single fast step, however big the map gets.
Creating a map
A map type is written map[KeyType]ValueType. Create one with a literal, or empty with make:
prices := map[string]int{
"sword": 120,
"potion": 15,
}
counts := make(map[string]int) // empty and ready to use
Keys must be comparable with ==: strings, numbers, booleans and arrays work, slices don't. Values can be anything, including slices and other maps.
Read, update and delete
inventory := map[string]int{"gold": 50, "gem": 3}
inventory["sword"] = 1 // add a new key
inventory["gold"] += 25 // update an existing one
delete(inventory, "gem") // remove (no error if it's missing)
fmt.Println(inventory["gold"], len(inventory))
fmt.Println(inventory["potion"]) // missing key
75 2
0
Reading a missing key doesn't fail — it returns the zero value of the value type. Handy, but then how do you tell "missing" apart from "stored as 0"?
The comma-ok idiom
An index expression can return a second value, a bool that reports whether the key exists:
stock := map[string]int{"gold": 75, "arrows": 0}
n, ok := stock["arrows"]
fmt.Println(n, ok) // 0 true
n, ok = stock["potion"]
fmt.Println(n, ok) // 0 false
if qty, found := stock["gold"]; found {
fmt.Println("gold in stock:", qty)
}
Iteration order is random
for key, value := range m visits every entry, but in an unspecified order that Go deliberately changes from run to run. When you need a stable order, collect the keys and sort them:
keys := make([]string, 0, len(stock))
for k := range stock {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, stock[k])
}
arrows 0
gold 75
nil maps and references
The zero value of a map is nil. A nil map behaves like an empty map for reading — lookups return the zero value, len is 0, range does nothing — but writing to it panics with assignment to entry in nil map. Always create a map with make or a literal before storing anything.
A map value is a reference to the underlying table. Assigning a map or passing it to a function doesn't copy the entries, so a function can add to the caller's map:
func addGold(inv map[string]int, amount int) {
inv["gold"] += amount // the caller sees this
}
Patterns: counting, sets and groups
Because missing keys read as 0, counting needs no special case:
counts := make(map[string]int)
for _, w := range []string{"gem", "gold", "gem", "gem"} {
counts[w]++
}
fmt.Println(counts) // map[gem:3 gold:1]
fmt prints maps with sorted keys, so this output is stable. A map[string]bool makes a simple set: seen[x] = true adds, seen[x] checks membership (missing keys read as false). A map[string]struct{} does the same without storing any values; test it with comma-ok. Maps of slices group values, and append works on the nil slice a missing key returns:
groups := make(map[string][]string)
for _, name := range []string{"Ada", "Bo", "Al"} {
first := name[:1]
groups[first] = append(groups[first], name)
}
fmt.Println(groups) // map[A:[Ada Al] B:[Bo]]
Common mistakes
- Writing to a nil map:
var m map[string]intfollowed bym["x"] = 1panics. Usemake. - Relying on iteration order: sort the keys when order matters, also in tests.
- Testing presence with the zero value:
m[k] == 0can't tell "missing" from "stored 0". Use comma-ok.
Assignment
Set up the guild hall's records. You'll need to import strings and sort (or slices).
WordCount(text string) map[string]intsplitstextinto words withstrings.Fields, lowercases each withstrings.ToLower, and returns how often each word appears. For text without words, return an empty map.Lookup(phonebook map[string]string, name string) (string, bool)returns the number stored fornameandtrue, or""andfalseifnameisn't in the phonebook. A name stored with an empty number is still present.UniqueSorted(words []string) []stringreturns each distinct word once, in alphabetical order.Invert(m map[string]int) map[int]stringreturns a new map from values to keys. If several keys share a value, keep the alphabetically smallest key, so the result is the same on every run.
WordCount("Gold gem GOLD gold") // map[gem:1 gold:3]
Lookup(map[string]string{"Ada": "555-0101"}, "Ada") // "555-0101", true
UniqueSorted([]string{"gem", "axe", "gem"}) // [axe gem]
Invert(map[string]int{"bo": 7, "ada": 7}) // map[7:ada]Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Maps and dictionaries in other languages
- JavaScript Map and Set · JavaScript
- Python Dictionaries: Keys, Values and Methods · Python
- Java HashMap: Key-Value Pairs · Java
- C# Dictionary<TKey, TValue> · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .