Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
How do Maps work internally in Go (Buckets, Hash Collisions, and Map Evacuation)?
senior LevelgolangGo Language Core
In Simple Words:
Go's map is a pointer to an hmap struct implementing an open-addressing hash table organized into Buckets:
- Each bucket holds up to 8 key-value pairs.
- Hash Lookup: Go hashes the key using AES or CityHash. The low bits determine the bucket index; the high 8 bits (top hash /
tophash) provide fast intra-bucket comparisons before checking the full key. - Overflow Buckets: If more than 8 keys hash to the same bucket, an overflow bucket is linked via a pointer.
- Map Growth & Evacuation:
- When the load factor exceeds 6.5 (average $> 6.5$ keys per bucket) or overflow buckets grow too large, Go doubles the bucket count ($2 imes$).
- Re-hashing is incremental (evacuation): elements are copied incrementally during subsequent writes/deletes to avoid stop-the-world latency spikes.
- Concurrency Trap: Maps are NOT thread-safe. Concurrent read and write triggers an unrecoverable runtime fatal panic:
fatal error: concurrent map writes. Usesync.RWMutexorsync.Map.