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.

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]Vis nil; reads return zero values, writes panic,lenis 0,deleteis a no-op, andrangeyields 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
recovercannot handle. - Map values are not addressable:
m[k].Field = 1does not compile; assign a modified copy back or store pointers. deleteremoves an entry but the table keeps its allocated buckets; deleting everything does not return the memory, andclear(m)keeps the capacity too.
Basic syntax and type signatures
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 keyThe type-level rules that matter:
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 keymap[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
| Approach | Concurrent reads | Concurrent writes | Type safety | When to use |
|---|---|---|---|---|
Plain map | safe | data race / fatal error | full | single goroutine, or external locking |
map + sync.Mutex | serialized | serialized | full | mixed read/write, simple |
map + sync.RWMutex | parallel | serialized | full | read-heavy with occasional writes |
sync.Map | safe | safe | any values | write-once keys, disjoint key sets |
| Channel-owned map | serialized by one goroutine | same | full | ownership model, actor-style |
| Sharded maps | parallel per shard | parallel per shard | full | high 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
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:
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 = 1The 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
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
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 fineThe 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
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 entryFloats 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
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 mapGo'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 symptom | Cause | Fix |
|---|---|---|
panic: assignment to entry in nil map | writing to a declared-but-uninitialized map | make it, or initialize in the constructor |
fatal error: concurrent map writes | unsynchronized writes from goroutines | mutex, channel ownership, or sync.Map |
fatal error: concurrent map read and map write | read during a write | RWMutex or copy under lock |
cannot assign to struct field m[k].F in map | map values are not addressable | modify a copy and reassign, or store pointers |
invalid map key type S | key type contains a slice, map, or func | use a comparable key or a string representation |
runtime error: hash of unhashable type | map[any] with a non-comparable dynamic type | restrict the key type |
| Lookup misses for equal-looking pointer keys | pointer keys compare addresses | key by value, or canonicalize pointers |
| Same key inserted repeatedly | NaN key | never key by floats |
| Iteration order changes between runs | maps randomize order | sort keys explicitly |
| Memory stays high after deleting everything | buckets are not released | replace 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.