Map Basics
Maps are Go's hash table / dictionary. They store key-value pairs with O(1) average lookup. Keys must be comparable types (strings, ints, etc. — not slices or maps).
// Create maps
scores := map[string]int{
"Alice": 95,
"Bob": 87,
"Charlie": 92,
}
// Or with make
ages := make(map[string]int)
ages["Alice"] = 30
ages["Bob"] = 25
fmt.Println(scores)
fmt.Println(ages["Alice"]) // 30
map[Alice:95 Bob:87 Charlie:92] 30
The Comma-OK Idiom
Accessing a missing key returns the zero value (0 for int, "" for string). To distinguish "key exists with zero value" from "key doesn't exist", use the comma-ok pattern:
scores := map[string]int{"Alice": 95, "Bob": 0}
// Bad: can't tell if Bob has score 0 or doesn't exist
score := scores["Charlie"]
fmt.Println(score) // 0 (missing key returns zero value)
// Good: comma-ok pattern
score, ok := scores["Bob"]
if ok {
fmt.Println("Bob's score:", score) // 0 (exists!)
}
score, ok = scores["Charlie"]
if !ok {
fmt.Println("Charlie not found") // Not in map
}
0 Bob's score: 0 Charlie not found
val, ok := m[key]. This is idiomatic Go and prevents bugs with zero values.Common Operations
m := map[string]int{"a": 1, "b": 2, "c": 3}
// Delete a key
delete(m, "b")
// Iterate (order is NOT guaranteed!)
for key, value := range m {
fmt.Printf("%s: %d\n", key, value)
}
// Length
fmt.Println("Size:", len(m))
⚠️ Common Mistake: Iterating maps in order
Map iteration order in Go is intentionally randomized. If you need sorted output, extract keys into a slice, sort it, then iterate.
Practice Exercises
Easy Hello World Variant
Modify the example to accept user input and print a personalized greeting.
Easy Code Reading
Read through the code examples above and predict the output before running them.
Medium Extend the Example
Take one code example and add error handling, input validation, or a new feature.