Nested Maps

Maps can contain other maps, allowing for complex nested data structures.

Example

A map where keys are first letters and values are maps of full names to their counts:

counts := map[rune]map[string]int{
    'b': {
        "billy": 2,
        "bob":   1,
    },
    'j': {
        "joe": 1,
    },
}

Initialization Warning

When working with nested maps, you must initialize the inner map before you can add values to it. Accessing a missing inner map returns nil, and trying to write to a nil map will cause a panic.

func add(m map[string]map[string]int, outer, inner string) {
    if _, ok := m[outer]; !ok {
        m[outer] = make(map[string]int) // Initialize the inner map
    }
    m[outer][inner]++
}