04 / 05

What happens when you write to a nil map vs an empty map?

Writing to a nil map causes a runtime panic. Reading from a nil map returns the zero value safely. An empty map initialized with make() is safe for both reads and writes.

Nil map vs empty map
Best practices
  1. 1

    Always initialize maps in struct constructors — do not rely on callers to initialize

  2. 2

    Use make(map[K]V, hint) with a size hint when the approximate number of entries is known

  3. 3

    Deleting from a nil map does NOT panic — delete() on nil map is a no-op

  4. 4

    len() on a nil map returns 0 without panic

  5. 5

    Range over a nil map produces zero iterations without panic