Skip to content

Maps

A map is a hash table that maps keys of type K to values of type V. Create one with make or a composite literal:

// make — preferred when you add entries incrementally
scores := make(map[string]int)
// composite literal — preferred when entries are known upfront
scores := map[string]int{
"Alice": 95,
"Bob": 87,
}

The key type must be comparable (supports ==). Valid key types include string, int, all numeric types, booleans, pointers, and structs whose fields are all comparable. Slices, maps, and functions cannot be used as keys.

scores["Charlie"] = 72 // set
fmt.Println(scores["Alice"]) // get → 95
delete(scores, "Bob") // delete (no-op if key absent)

Reading a key that does not exist never panics — it returns the zero value for the value type:

fmt.Println(scores["Dave"]) // 0 — not a panic

This is convenient but can hide bugs: you cannot tell whether a key maps to 0 or was never set. Use the comma-ok idiom to distinguish.

A two-result map lookup returns the value and a boolean indicating whether the key was present:

v, ok := scores["Dave"]
if !ok {
fmt.Println("Dave not found")
}

Assigning a map copies the header, not the data. Both variables point to the same underlying hash table:

a := map[string]int{"x": 1}
b := a
b["x"] = 99
fmt.Println(a["x"]) // 99 — a and b share the same map

Go deliberately randomizes map iteration order on every run to prevent code from depending on an undefined order. To print map entries deterministically, sort the keys first:

import "sort"
keys := make([]string, 0, len(scores))
for k := range scores {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%s: %d\n", k, scores[k])
}
package main
import (
"fmt"
"sort"
)
func main() {
// make a map and add entries
scores := make(map[string]int)
scores["Alice"] = 95
scores["Bob"] = 87
scores["Charlie"] = 72
// Comma-ok idiom
v, ok := scores["Bob"]
fmt.Println(v, ok) // 87 true
v2, ok2 := scores["Dave"]
fmt.Println(v2, ok2) // 0 false
// Delete an entry
delete(scores, "Charlie")
// Sort keys for deterministic output
keys := make([]string, 0, len(scores))
for k := range scores {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%s: %d\n", k, scores[k])
}
}
You read `scores["Dave"]` but "Dave" was never added. What does Go return?
What does the second return value in `v, ok := scores["Alice"]` tell you?
You assign `b := a` where a is a `map[string]int`. You then set `b["x"] = 99`. What is `a["x"]`?
Why does Go randomize map iteration order?