2026-10-31·作者 Sijie Wang

Map

Map: a built-in hash table with reference semantics

The motivation: the most-used structure, built into the language. A Go map is not a library type; it is a hash table the language itself provides, written as a literal. That is why its semantics deserve a node of their own: three of them surprise people who arrive from other languages.

Reference semantics: the variable is a pointer. A map variable points at the underlying hash table. Assignment and passing copy the pointer, not the data, so a function that writes into a map it received changes the caller's map too. This matches a slice and is the opposite of an array, which copies its contents.

Concurrent writes are fatal, not an exception. Two goroutines writing to the same map at once make the runtime throw concurrent map writes, and the whole process dies. There is nothing to catch. The comparison with Java is instructive: Java's HashMap fails fast with a ConcurrentModificationException, which can be caught, and some concurrent writes do not even throw but silently lose data or, in old versions, loop forever on resize. Go chose the harsher side: detect and kill the process. A map shared across goroutines is therefore always guarded by a mutex, or replaced by sync.Map.

Iteration order is randomized on purpose. Each range picks a random starting bucket and a random offset inside it, so the order differs from run to run. Note what is randomized: only the iteration start, not the storage. Which bucket a key lives in is still decided by its hash. The purpose is to stop code from depending on order: a fixed order would let order-dependent code pass tests today and silently break when a hash seed changes, a growth happens, or a Go version ships. Randomization makes order-dependent code flaky during development, forcing the honest fix: collect the keys, sort them, then look values up in sorted order.

Production note. Never depend on map iteration order, and never share a map across goroutines without a guard. Both rules come from the same root: a map is a shared mutable table, and Go gives you the speed of that table together with the responsibility for guarding it.

关于这一条

sijie 的一条 wiki 条目。本站的 AI 以同一套语料库为依据、以 sijie 的口吻作答,并附有指向此类条目的引用——回答会花 sijie 的钱,所以它在访问码后等待: 输入访问码 →