[Go] Assign to a nested map without a nil map panic

Created on November 29, 2026

Initializing the outer map leaves its inner maps uninitialized. Reading a missing entry from the outer map returns a nil inner map, so assigning a value through that entry causes panic: assignment to entry in nil map.

Reproduce the panic

package main

func main() {
    scores := map[string]map[string]int{}
    scores["Tom"]["math"] = 90
}

The first line of the error is:

panic: assignment to entry in nil map

Initialize the inner map before assigning

Test whether the inner map is nil. This also handles an outer key that exists but has a nil value.

package main

import "fmt"

func main() {
    scores := map[string]map[string]int{}
    if scores["Tom"] == nil {
        scores["Tom"] = map[string]int{}
    }
    scores["Tom"]["math"] = 90
    fmt.Println(scores)
}

Assign an inner map with its initial value

You can also create the inner map with its first entry in a single assignment. If an inner map already exists, update the entry in place to preserve its other values.

package main

import "fmt"

func main() {
    scores := map[string]map[string]int{}
    if scores["Tom"] == nil {
        scores["Tom"] = map[string]int{"math": 90}
    } else {
        scores["Tom"]["math"] = 90
    }
    fmt.Println(scores)
}

Both fixes print the same result.

map[Tom:map[math:90]]
Go