07 - Collections: Maps
📋 Jump to TakeawaysSlices are great when you have a list of things in order. But sometimes you need to look something up by name. "What's Alice's phone number?" or "How many times does the word 'the' appear?" You don't want to search through a list for that. You want to ask by name and get the answer directly.
That's what a map does. It stores key-value pairs.
Creating a Map
ages := map[string]int{
"Alice": 30,
"Bob": 25,
"Carol": 28,
}
fmt.Println(ages) // map[Alice:30 Bob:25 Carol:28]map[string]int means "a map where keys are strings and values are integers."
Here we used string keys, but keys can be any comparable type — int, bool, or even your own types later. For example, a map from student ID to name:
students := map[int]string{
26001: "Alice",
26012: "Bob",
}You can also create an empty map and add to it:
ages := map[string]int{}
ages["Alice"] = 30
ages["Bob"] = 25Or with make:
ages := make(map[string]int)
ages["Alice"] = 30Accessing Values
ages := map[string]int{"Alice": 30, "Bob": 25}
fmt.Println(ages["Alice"]) // 30
fmt.Println(ages["Eve"]) // 0If a key doesn't exist, Go returns the zero value for the map's value type: 0 if values are int, "" if string, false if bool. This means you can't tell the difference between "the key exists with value 0" and "the key doesn't exist" just by looking at the value.
The Comma-Ok Pattern
To check if a key actually exists, use the two-value form:
age, ok := ages["Alice"]
fmt.Println(age, ok) // 30 true
age, ok = ages["Eve"]
fmt.Println(age, ok) // 0 falseok is true if the key exists, false if it doesn't. Use it in an if:
if age, ok := ages["Alice"]; ok {
fmt.Printf("Alice is %d\n", age)
} else {
fmt.Println("Alice not found")
}Updating and Deleting
ages["Alice"] = 31 // update
delete(ages, "Bob") // deleteDeleting a key that doesn't exist does nothing. No error, no crash.
Looping Over Maps
for name, age := range ages {
fmt.Printf("%s is %d\n", name, age)
}Map iteration order is random in Go. If you need a specific order, sort the keys first.
Maps vs Slices
| Slice | Map | |
|---|---|---|
| Access by | Index (0, 1, 2...) | Key (any type) |
| Order | Maintained | Random |
| Best for | Lists, sequences | Lookups, properties |
Key Takeaways
map[keyType]valueTypecreates a map. Keys must be comparable types (strings, ints, bools)- Access values with
m[key]. Missing keys return the zero value - Use the comma-ok pattern to check if a key exists:
val, ok := m[key] delete(m, key)removes a key. Deleting a missing key is saferangeover a map gives key and value. Order is random- Use slices for ordered lists, maps for lookups by name