>_
GolangStepByStep
Intern

Maps

Key-value lookups with hash maps — create, read, delete, iterate

# Why Maps Matter

Maps are the default structure for fast lookup in Go services: caching, counters, deduplication, grouping, indexes, and request-scoped metadata.

The biggest mistakes are writing to nil maps, assuming stable iteration order, and unsafely sharing maps across goroutines.

Real-World Analogyclick to expand

A map is like a locker room where each locker key maps to one compartment. You can quickly jump to the right compartment by key, but the order of walking lockers is not meaningful.

# Creating and Initializing Maps

A map variable's zero value is nil. Reads are safe, writes panic. Initialize before writing.

scores := map[string]int{"Alice": 95}
scores["Bob"] = 87

var m map[string]int
fmt.Println(m["x"]) // 0 (safe read)
// m["x"] = 1        // panic on write

# Comma-Ok, Delete, and Zero Values

Missing keys return the value type's zero value, so use comma-ok when presence matters.

m := map[string]int{"go": 1}

v, ok := m["go"]     // ok=true, v=1
v, ok = m["python"]  // ok=false, v=0

delete(m, "go")      // safe even if absent

# Iteration Order and Deterministic Output

Map iteration order is intentionally randomized. For deterministic output, sort keys first.

freq := map[string]int{"go": 3, "rust": 2, "python": 1}

keys := make([]string, 0, len(freq))
for k := range freq {
    keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
    fmt.Println(k, freq[k])
}

# Real-World Example: Word Frequency Counter

Counting words is a classic map use case and demonstrates zero-value increment patterns.

package main

import (
    "fmt"
    "strings"
)

func WordCount(s string) map[string]int {
    freq := make(map[string]int)
    for _, word := range strings.Fields(strings.ToLower(s)) {
        freq[word]++
    }
    return freq
}

func main() {
    counts := WordCount("the cat sat on the mat the cat")
    fmt.Println(counts["the"]) // 3
    fmt.Println(counts["cat"]) // 2
}

⚡ Key Takeaways

  • Initialize maps before writing; nil map writes panic
  • Use comma-ok when key existence matters
  • Do not rely on iteration order; sort keys for deterministic output
  • Map writes are not safe concurrently without synchronization
practice & review