Go Maps: Your Built-in Hash Table
Go maps are the language's built-in hash tables for fast key-value lookups. Use `make(map[K]V)` to initialize one before writing. The biggest footgun is writing to a `nil` map, which causes a runtime panic. Always initialize your maps first.
WHY IT EXISTS Nearly every program needs to associate data with a unique identifier. Go provides a built-in map type to solve this common problem, implementing a hash table directly in the language for efficient key-value storage and retrieval without needing an external library.
THE MENTAL MODEL A Go map is a reference to a hash table, not the data structure itself. Think of var m map[string]int as declaring a signpost that currently points to nowhere (nil). You can't add data to a non-existent location. You must first use make or a map literal to create the underlying hash table structure, and then point your variable to it.
HOW IT WORKS To use a map, you must first initialize it. A declared-only map is nil. Writing to a nil map causes a runtime panic. Initialize using m := make(map[string]int) or a literal like commits := map[string]int{"rsc": 3711}.
Once initialized, you can perform common operations. Set a value with m["key"] = 100. Retrieve a value with v := m["key"]. If the key doesn't exist, v will be the zero value for its type (e.g., 0 for int, false for bool, "" for string). To distinguish a stored zero from a non-existent key, use the two-value assignment: value, ok := m["key"]. The ok boolean will be true only if the key exists. You can delete an entry with delete(m, "key") and get the number of items with len(m). Iterate over a map using for key, value := range m.
WHEN TO USE IT Use a map whenever you need fast lookups, additions, or deletions based on a key. This is ideal for tasks like implementing a cache, storing configuration settings, or tracking visited items in a set-like fashion, where the key's presence is all that matters.
WHEN NOT TO USE IT Do not use types that are not comparable as map keys. Slices, functions, and other maps cannot be keys because their values are not uniquely comparable with the == operator. Also, the iteration order of a map is not guaranteed and may change between runs. Do not rely on a stable order when looping over a map.
ONE CANONICAL EXAMPLE You can use a map as a set to detect cycles in a data structure. By creating a visited := make(map[*Node]bool), you can traverse a linked list. Before visiting a node n, you check if visited[n]. If it's true, you've found a cycle. If false (the zero value for bool), you mark it as visited with visited[n] = true and continue. This works because a lookup for a non-existent key returns false.
Read the original → go.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.