Maps
A map is an unordered hash table from keys to values: map[K]V. Keys must be comparable. The zero map is nil and is safe to read, not to write.
Detailed Explanation
You are counting requests per path. counts := map[string]int{} or make(map[string]int) gives you a table. counts[path]++ inserts or updates. There is no separate "put" method. Maps are the dictionary of the language.
Keys. K must support ==: numbers, strings, pointers, arrays, structs of comparable fields, interfaces (with a runtime panic if the dynamic value is not comparable). Slices, maps, and functions cannot be keys. If you need a slice key, use a string (join with a separator you control) or a comparable struct.
Nil maps. var m map[string]int is nil. m[k] returns the zero V. m[k] = v panics. len(m) is 0. range m is a no-op. make or a literal is required before the first write. This is the same zero-value story as channels, and the opposite of slices (which you can append to when nil).
Lookup and delete. v := m[k] is the zero when k is missing — you cannot tell a missing int from a stored 0 without the comma-ok form. delete(m, k) is a no-op if the key is absent or m is nil. There is no delete return value.
Iteration is randomized. Each range visits every key once, in an unpredictable order. Tests that print a map will flake if they expect a fixed sequence. Sort the keys when order matters.
Not safe for concurrent write. Two goroutines writing (or one writing and one reading) without a lock is a data race and, in Go, often a runtime fatal "concurrent map write." Use sync.Mutex, sync.RWMutex, or sync.Map when the map is shared.
What it costs. Average insert and lookup are constant time. The table grows by allocating new buckets. A map[string]T stores the string header and hashes the bytes. For a hot inner loop with integer keys, a slice can be faster if the key space is dense. Pre-size with make(map[K]V, n) when you know n.
Code Examples
package main
import "fmt"
func main() {
counts := make(map[string]int)
counts["/health"]++
fmt.Println(counts["/health"], counts["/missing"]) // 1 0
delete(counts, "/health")
fmt.Println(len(counts))
}func fromLiteral() map[int]string {
return map[int]string{1: "one", 2: "two"}
}func nilRead() {
var m map[string]int
fmt.Println(m["x"]) // 0
// m["x"] = 1 // panic
}Common Gotchas
Assignment to a nil map panics
`make` or a literal first.
Concurrent write (or write+read) crashes or races
lock, or do not share.
Missing keys look like zero values
use comma-ok when `0`, `""`, or `nil` is a real stored value.
Map values are not addressable
`&m[k]` does not compile. Store pointers if you must mutate in place.