Ad Space — Top Banner

assignment to entry in nil map

Go Programming Language

Severity: Critical

What Does This Error Mean?

You are trying to write to a map that was never initialized. Declaring a map variable does not create the map — you must use make(). This is one of the most common Go beginner mistakes.

Affected Models

  • Go 1.21
  • Go 1.22
  • Go 1.23
  • Go 1.24

Common Causes

  • Declaring a map with var m map[string]int but forgetting to initialize it with make()
  • A struct field that is a map type, used before the struct is initialized
  • A function that returns a map pointer, which is nil on an error path
  • Copying a struct that contains an uninitialized map field
  • Using a map from JSON unmarshaling before checking that the key exists

How to Fix It

  1. Replace var m map[string]int with m := make(map[string]int).

    make() allocates the map and makes it ready for use. Without make(), m is nil.

  2. Alternatively, use a map literal: m := map[string]int{}

    Both make(map[string]int) and map[string]int{} create an initialized, empty map. Use either.

  3. For struct fields that are maps, initialize them in a constructor function.

    func NewConfig() Config { return Config{Tags: make(map[string]string)} } — always initialize map fields before use.

  4. Add a nil check if the map might be uninitialized in some code paths.

    if m == nil { m = make(map[string]int) } — this is a safe guard before writing to a map.

  5. Reading from a nil map is safe in Go — only writing panics.

    var m map[string]int; v := m["key"] returns 0 (zero value) without panicking. Writing is the problem.

When to Call a Professional

This error is almost always a straightforward fix — no need to escalate. If you see it in complex code with many struct layers, ask a colleague to help trace where initialization should happen.

Frequently Asked Questions

Why does var m map[string]int not create a usable map?

var creates a variable with its zero value. The zero value of a map type is nil — not an empty map. You must call make() to actually allocate the map in memory.

Can I read from a nil map without panicking?

Yes. Reading from a nil map returns the zero value for the value type. var m map[string]int; fmt.Println(m["key"]) prints 0 — no panic. Only writes to a nil map cause a panic.

What is the difference between make(map[K]V) and map[K]V{}?

They both create an initialized, empty map. The result is the same. make(map[K]V, hint) lets you pass an initial capacity hint for performance. map[K]V{} is more concise for most use cases.