Explain it simply
Explain it simply
Think of a map as a dictionary. If you know the word (the key) you can jump straight to its meaning (the value) without turning every page. In Go, map[string]int is a dictionary where each string key has one int value.
This dictionary has two odd habits, though. Look up a word that is not in it and, instead of saying "not found", it hands back an empty meaning, the zero value. And its pages are not in alphabetical order; the order can differ every time you flip through it.
Problem → Why → Solution
The problem: out of stock, or a misspelled product?
Say a shop keeps its stock in a map. A customer types "cofee" with a typo, and stock["cofee"] returns 0. The program announces "sold out" when it should have said there is no such product. Tea really is sold out and also reads 0, so the two zeros cannot be told apart.
package main
import "fmt"
func main() {
stock := map[string]int{"coffee": 12, "tea": 0}
for _, item := range []string{"tea", "cofee"} {
if stock[item] == 0 {
fmt.Println(item, "is sold out") // wrong for "cofee"
}
}
}Why does it return 0?
Reading a missing key from a Go map does not error or panic; it returns the zero value of the value type, 0 for int and "" for string. That is convenient for counting, but it does not answer "is the key present?". The answer is the comma-ok form, qty, ok := stock[item], where ok is true only when the key exists.
Core concept: key-to-value lookup and its rules
A map type is written map[K]V. The key type K must be comparable with ==: string, int, bool, arrays, and structs whose fields are all comparable. Slices, maps and functions cannot be keys; map[[]string]int is an "invalid map key type" compile error. The value type V can be anything.
Create a map with a literal such as map[string]int{"Aung": 90} or with make(map[string]int). m[key] = value inserts or replaces, delete(m, key) removes (and does nothing if the key is absent), and len(m) counts the entries. A bare var m map[string]int is a nil map. Reading from it, taking its len and ranging over it are all safe, but the first write panics with "panic: assignment to entry in nil map".
The order of ranging over a map is not defined by the Go spec, and the runtime deliberately randomizes it, so it can change from one run to the next. fmt.Println(m), on the other hand, sorts the keys before printing, so its output is stable. To loop in order yourself, get a sorted key slice with slices.Sorted(maps.Keys(m)) and range over that.
A map value does not hold the data itself; it refers to an internal hash table. Assigning a map to another variable or passing it to a function shares that one table, so changes made inside a function are visible to the caller. Use maps.Clone when you need an independent copy. One last rule: writing to a map from several goroutines at once makes the runtime stop with a "concurrent map writes" fatal error, which later lessons solve with sync.Mutex.
- Key is hashed to find its slot
- Found: value and ok = true
- Missing: zero value and ok = false
- Need order? Sort the keys first
Every lookup asks two questions, "what is the value?" and "is the key there?"; comma-ok answers both.
General pattern
m := map[KeyType]ValueType{key1: value1}
m := make(map[KeyType]ValueType)
m[key] = value // insert or replace
v := m[key] // zero value if missing
v, ok := m[key] // ok is false if missing
delete(m, key) // no-op if missing
n := len(m)
for _, k := range slices.Sorted(maps.Keys(m)) { use(k, m[k]) }Use comma-ok whenever presence matters. Map iteration order is random, so when order matters, sort the keys first as the last line shows.
Example: a map of scores
This program builds a map from names to scores, adds an entry, reads an existing and a missing key with comma-ok, deletes an entry, and prints in sorted key order. Every line of its output is the same on every run. Before running it, decide what the lookup of Zaw will print.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
scores := map[string]int{
"Aung": 90,
"Su": 85,
}
scores["Mya"] = 95
score, exists := scores["Su"]
fmt.Println("Su score:", score)
fmt.Println("Exists:", exists)
score, exists = scores["Zaw"]
fmt.Println("Zaw score:", score, "exists:", exists)
delete(scores, "Aung")
fmt.Println(scores, len(scores))
for _, name := range slices.Sorted(maps.Keys(scores)) {
fmt.Println(name, scores[name])
}
}Code breakdown
- Literal
scores := map[string]int{A map from string keys to int values. Each entry in the literal ends with a comma, including the last line.
- Insert
scores["Mya"] = 95A new key, so a new entry is added. If the key already existed, its value would be replaced.
- Comma-ok
score, exists := scores["Su"]Su exists, so score is 85 and exists is true. The later lookup of Zaw gives 0 and false, and exists is what tells you that 0 means "absent", not a real score.
- Delete
delete(scores, "Aung")Removes Aung, so len becomes 2. fmt.Println sorts the keys and prints map[Mya:95 Su:85].
- Sorted loop
for _, name := range slices.Sorted(maps.Keys(scores)) {maps.Keys yields the keys as an iterator and slices.Sorted collects them into a sorted slice, so Mya 95 always prints before Su 85.
Su score: 85
Exists: true
Zaw score: 0 exists: false
map[Mya:95 Su:85] 2
Mya 95
Su 85Maps share their data
addBonus() receives the map as a parameter and adds 5 to every value. Unlike an array, the caller's scores change too, because both refer to the same table. The backup taken with maps.Clone is a separate table, so it stays as it was. Updating existing keys' values, or deleting entries, while ranging over a map is safe.
package main
import (
"fmt"
"maps"
)
func addBonus(scores map[string]int) {
for name := range scores {
scores[name] += 5
}
}
func main() {
scores := map[string]int{"Aung": 90, "Su": 85}
backup := maps.Clone(scores)
addBonus(scores)
fmt.Println(scores) // map[Aung:95 Su:90]
fmt.Println(backup) // map[Aung:90 Su:85]
}In real projects
Where this shows up in real projects
Maps appear wherever you need a lookup table: product ID to price, HTTP header name to values (http.Header is a map[string][]string), config key to setting, session token to user ID. A map[string]Product is a common in-memory cache that saves trips to the database, and map[string]bool or map[string]struct{} serves as a "set" for checking processed IDs or duplicate emails.
Random iteration order is a classic cause of flaky tests: a test for a function that ranges over a map to build report lines passes one run and fails the next. So sort the keys for anything shown to users, written to files, or compared in tests. In programs that run many goroutines at once, such as web servers, writing to a shared map without a lock can crash the whole server, so it must be guarded with sync.Mutex.
Common mistakes
Common mistakes
1. Writing to a nil map
After var stock map[string]int, the line stock["tea"] = 5 panics with "assignment to entry in nil map". This often happens with a map field inside a struct. Initialize any map you will write to with make(map[string]int) or map[string]int{} first.
2. Treating the zero value as "missing"
if stock[item] == 0 cannot tell a missing key from a value that really is 0. When presence matters, use comma-ok: if qty, ok := stock[item]; !ok { ... }.
3. Relying on range order
Treating the first key from a range as "the smallest", or hard-coding range output order in a test, produces bugs that fail only some of the time. Sort the keys with slices.Sorted(maps.Keys(m)) and loop over those.
Best practices
Best practices
- When you know roughly how many entries are coming, give make(map[string]int, n) a size hint to avoid repeated growth.
- For a set, use map[string]struct{}: the empty struct takes no memory and the map records only presence.
- Initialize map fields of a struct in a constructor function so nobody hits the nil-map panic.
- When you return a map to a caller, remember the caller can modify it; hand out a maps.Clone copy if that matters.
Mini challenge
Mini challenge: a word counter
Count how often each word appears in a sentence and find the most frequent one. The output must be identical on every run.
- countWords(text string) map[string]int splits with strings.Fields, ignoring case via strings.ToLower
- topWord(counts map[string]int) (string, int) breaks ties by picking the alphabetically first word
- main() prints every word in sorted order
- Nothing may depend on the order of ranging over the map
package main
import (
"fmt"
"maps"
"slices"
"strings"
)
func countWords(text string) map[string]int {
// TODO: make the map, lower-case the text,
// split it into words and count each one
_ = strings.Fields
return nil
}
func topWord(counts map[string]int) (string, int) {
// TODO: walk the keys in sorted order; keep the first highest count
_ = slices.Sorted(maps.Keys(counts))
return "", 0
}
func main() {
counts := countWords("Go is fun and go is fast and Go is simple")
// TODO: print "word count" lines in sorted order, then "top: word n"
fmt.Println(len(counts))
}Expected: and 2 fast 1 fun 1 go 3 is 3 simple 1 top: go 3
Show hint
counts[word]++ starts from 0 for a missing key, so no if is needed. In topWord, walk the sorted keys and compare with > (not >=) so the first word wins a tie.
Show solution
package main
import (
"fmt"
"maps"
"slices"
"strings"
)
func countWords(text string) map[string]int {
counts := make(map[string]int)
for _, word := range strings.Fields(strings.ToLower(text)) {
counts[word]++
}
return counts
}
func topWord(counts map[string]int) (string, int) {
best, bestCount := "", 0
for _, word := range slices.Sorted(maps.Keys(counts)) {
if counts[word] > bestCount {
best, bestCount = word, counts[word]
}
}
return best, bestCount
}
func main() {
counts := countWords("Go is fun and go is fast and Go is simple")
for _, word := range slices.Sorted(maps.Keys(counts)) {
fmt.Println(word, counts[word])
}
word, n := topWord(counts)
fmt.Println("top:", word, n)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- In map[K]V, K must be comparable; work with m[key] = value, delete(m, key) and len(m).
- A missing key reads as the zero value, so use value, ok := m[key] when presence matters.
- Reading a nil map is safe but writing panics, so initialize maps with make() or a literal.
- Range order is random, so sort with slices.Sorted(maps.Keys(m)) when order matters, and remember that passing a map shares its data.
A Tour of Go — Go