Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Maps: Hash Map Internals, Concurrency Safety, and delete Operations

Nil map semantics, comparability rules for keys, concurrent access that kills the process, non-addressable values, and growth that never shrinks.

~6 min readGo
#Go#Data Structures#Memory
3D illustration of Go hash map buckets allocating key-value pairs with concurrency shields and delete indicators

A Go map is a hash table whose zero value is nil. Reading from a nil map returns the zero value of the element type, writing to one panics, and the compiler cannot tell the two cases apart at the call site — which is why the first bug in most map code is assignment to entry in nil map. Beyond that, maps are reference types with randomized iteration, they are not safe for concurrent writes, and their keys must be comparable, a constraint that rejects slices, maps, and functions at compile time and produces surprising behavior for floats.

Quick Summary

  • var m map[K]V is nil; reads return zero values, writes panic, len is 0, delete is a no-op, and range yields nothing.
  • A map is a reference type: assigning or passing it copies a header that points at the same table, so mutations are visible to every holder.
  • Reading a missing key returns the zero value; use the comma-ok form (v, ok := m[k]) when zero and absent must be distinguished.
  • Map keys must be comparable. A struct with a slice, map, or function field is rejected at compile time; a pointer key compares addresses, not pointees.
  • Iteration order is randomized per range and must never be relied on; sorting keys is the only deterministic option.
  • Concurrent writes, or a write concurrent with a read, cause a fatal runtime error that recover cannot handle.
  • Map values are not addressable: m[k].Field = 1 does not compile; assign a modified copy back or store pointers.
  • delete removes an entry but the table keeps its allocated buckets; deleting everything does not return the memory, and clear(m) keeps the capacity too.

Basic syntax and type signatures

go
m := make(map[string]int) // empty, non-nil n := map[string]int{"a": 1} // literal var z map[string]int // nil p := make(map[string]int, 1000) // capacity hint v := m["a"] // zero value if absent v, ok := m["a"] // presence check m["b"] = 2 delete(m, "a") clear(m) // Go 1.21+, empties but keeps allocation for k, v := range m { _ = k; _ = v } // order is randomized for k := range m { _ = k } type Point struct{ X, Y int } grid := map[Point]string{{0, 0}: "origin"} // comparable struct key

The type-level rules that matter:

go
type Bad struct{ Items []int } // var m map[Bad]int // compile error: invalid map key type Bad type Good struct{ ID string; N int } var m2 map[Good]int // ok: all fields comparable var m3 map[*Point]int // ok: pointer keys compare addresses var m4 map[any]int // ok to declare; panics at runtime on a slice key

map[any]V is the dangerous one: it compiles, and inserting a value whose dynamic type is not comparable panics with runtime error: hash of unhashable type []int. The compiler only checks the static key type, so an interface key moves the check to runtime.

Comparison of map implementations for shared state

ApproachConcurrent readsConcurrent writesType safetyWhen to use
Plain mapsafedata race / fatal errorfullsingle goroutine, or external locking
map + sync.Mutexserializedserializedfullmixed read/write, simple
map + sync.RWMutexparallelserializedfullread-heavy with occasional writes
sync.Mapsafesafeany valueswrite-once keys, disjoint key sets
Channel-owned mapserialized by one goroutinesamefullownership model, actor-style
Sharded mapsparallel per shardparallel per shardfullhigh contention, many cores

sync.Map is not a drop-in upgrade: its API takes any, every read returns (any, bool) requiring a type assertion, and its optimized cases are keys written once and read many times, or goroutines operating on disjoint key sets. For ordinary read-heavy caches with a mutex, RWMutex around a plain map is faster and clearer, and the compiler checks the value types.

Practical edge cases and deep dives

1. Nil maps, comma-ok, and the zero value

go
type Registry struct { entries map[string]*Service } func (r *Registry) Add(name string, s *Service) { r.entries[name] = s // panic: assignment to entry in nil map } func (r *Registry) AddFixed(name string, s *Service) { if r.entries == nil { r.entries = make(map[string]*Service) } r.entries[name] = s } func Lookup(r *Registry, name string) (*Service, bool) { if r.entries == nil { return nil, false } s, ok := r.entries[name] return s, ok }

The nil write panic is the reason constructors exist: func NewRegistry() *Registry { return &Registry{entries: make(map[string]*Service)} } puts the initialization in one place and makes the zero value unusable on purpose. Note that reading a missing key from a non-nil map returns nil for a pointer element and 0 for an int, with no error — so a map of counts cannot distinguish "no entry" from "count zero" without the comma-ok form:

go
counts := map[string]int{"a": 0} fmt.Println(counts["b"]) // 0, indistinguishable from counts["a"] if v, ok := counts["b"]; ok { _ = v } // ok == false counts["b"]++ // works even when absent: 0 + 1 = 1

The increment idiom is the one place the zero value is exactly right, because a missing counter and a zero counter want the same behavior.

2. Concurrent access is a fatal error, not a panic

go
func broken() { m := make(map[int]int) var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func(i int) { defer wg.Done() for j := 0; j < 1000; j++ { m[i*1000+j] = j // fatal error: concurrent map writes } }(i) } wg.Wait() } type Safe struct { mu sync.RWMutex m map[string]int } func (s *Safe) Get(k string) (int, bool) { s.mu.RLock() defer s.mu.RUnlock() v, ok := s.m[k] return v, ok } func (s *Safe) Set(k string, v int) { s.mu.Lock() defer s.mu.Unlock() if s.m == nil { s.m = make(map[string]int) } s.m[k] = v }

The runtime detects concurrent writes with a check on the map header and throws fatal error: concurrent map writes, which unwinds the whole program; recover does not catch it. A read racing a write produces fatal error: concurrent map read and map write. The race detector (go test -race) finds the same bug earlier with a stack trace instead of a crash, and it should be part of any test run that exercises goroutines.

3. Map values are not addressable

go
type User struct { Name string Login int } users := map[string]User{"a": {Name: "A"}} // users["a"].Login++ // compile error: cannot assign to struct field users["a"].Login in map // read-modify-write u := users["a"] u.Login++ users["a"] = u // or store pointers ptrs := map[string]*User{"a": {Name: "A"}} ptrs["a"].Login++ // ok: the pointer is a copy, the pointee is shared // slices inside maps are the same trap one level down groups := map[string][]string{} // groups["x"] = append(groups["x"], "y") // this is actually fine

The rule is that map elements are not variables, so they have no address and cannot be assigned to field-by-field. append(groups[k], v) works because append returns a new slice header that is assigned back to the map entry, which is the same read-modify-write pattern written compactly. A map of mutexes is worse: m[k].Lock() does not compile for the same reason, which is why shared state is stored as map[string]*entry with the mutex inside the pointer.

4. Keys that compare unexpectedly

go
type Key struct{ A, B string } m := map[Key]int{{"x", "y"}: 1} type WithSlice struct { ID string Parts []string } // var bad map[WithSlice]int // invalid map key type WithSlice p1, p2 := &Key{"a", "b"}, &Key{"a", "b"} pm := map[*Key]int{p1: 1} fmt.Println(pm[p2]) // 0: different addresses, different keys nan := math.NaN() fm := map[float64]int{} fm[nan] = 1 fmt.Println(fm[nan], len(fm)) // 0 1 — inserted, unreachable fm[nan] = 2 fmt.Println(len(fm)) // 2 — every NaN insert creates a new entry

Floats are legal keys because they are comparable, but NaN != NaN means a NaN key can be inserted repeatedly and never found; -0.0 and 0.0 compare equal and hash the same, so they collide. Struct keys compare field by field and hash all fields, so any field that changes changes the identity — a map keyed by a struct that contains a time.Time (which contains a monotonic clock reading) is a subtle source of misses after deserialization. For pointer keys, use the pointed-to value as the key or maintain a canonical map from value to pointer.

5. Growth, deletion, and memory that does not come back

go
m := make(map[int]int, 10000) // pre-size: fewer rehashes while filling for i := 0; i < 10000; i++ { m[i] = i } for k := range m { delete(m, k) // safe during range; entries deleted before visit are skipped } fmt.Println(len(m)) // 0 for i := 0; i < 1000000; i++ { m[i] = i } for k := range m { delete(m, k) // length drops to 0, buckets stay allocated } // m still holds the bucket array sized for a million entries; use clear(m) or a new map

Go's map grows by allocating a new bucket array and evacuating entries when the load factor is exceeded (6.5 entries per bucket in the classic implementation; Go 1.24 replaced the internals with a Swiss-table design while keeping the same API and semantics). Shrinking is not part of the contract: delete clears slots but the array keeps its size, so a cache that grows to a million entries and then empties leaves that memory allocated. Replacing the map (m = make(map[K]V)) or calling clear(m) returns the entries to the garbage collector only for the values, not the buckets; the map's peak size is effectively its long-term size.

Preallocation matters for a different reason than in slices: a map with a size hint allocates enough buckets up front and avoids the incremental evacuation that makes a large fill noticeably slower. The hint is not a cap — the map still grows past it.

Common mistakes and compiler errors

Error or symptomCauseFix
panic: assignment to entry in nil mapwriting to a declared-but-uninitialized mapmake it, or initialize in the constructor
fatal error: concurrent map writesunsynchronized writes from goroutinesmutex, channel ownership, or sync.Map
fatal error: concurrent map read and map writeread during a writeRWMutex or copy under lock
cannot assign to struct field m[k].F in mapmap values are not addressablemodify a copy and reassign, or store pointers
invalid map key type Skey type contains a slice, map, or funcuse a comparable key or a string representation
runtime error: hash of unhashable typemap[any] with a non-comparable dynamic typerestrict the key type
Lookup misses for equal-looking pointer keyspointer keys compare addresseskey by value, or canonicalize pointers
Same key inserted repeatedlyNaN keynever key by floats
Iteration order changes between runsmaps randomize ordersort keys explicitly
Memory stays high after deleting everythingbuckets are not releasedreplace the map, or bound its size

Two habits prevent most of these. First, always construct maps in a constructor or with a literal, and treat a nil map as a value that is never written — the panic is a design signal, not a runtime accident to patch. Second, decide the concurrency story when the map is created: a map that lives in a struct shared across goroutines needs its lock next to it, and a map that is only ever touched by one goroutine should stay a local so no one adds a second writer later.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.