How to Create Nested Map in Go: Syntax and Example
In Go, you create a nested map by declaring a map whose values are also maps, like
map[string]map[string]int. Initialize the outer map first, then initialize inner maps before assigning values to avoid nil map errors.Syntax
A nested map in Go is a map where each value is itself another map. The general syntax looks like this:
map[KeyType]map[InnerKeyType]ValueTypedeclares a nested map.- The outer map's keys are of type
KeyType. - The inner map's keys are of type
InnerKeyType. - The inner map's values are of type
ValueType.
You must initialize the outer map first, then initialize each inner map before adding values.
go
var nestedMap map[string]map[string]int nestedMap = make(map[string]map[string]int)
Example
This example shows how to create a nested map where the outer keys are strings, inner keys are strings, and values are integers. It initializes the maps and assigns values safely.
go
package main import "fmt" func main() { // Declare and initialize the outer map nestedMap := make(map[string]map[string]int) // Initialize inner map for key "fruits" nestedMap["fruits"] = make(map[string]int) nestedMap["fruits"]["apple"] = 5 nestedMap["fruits"]["banana"] = 3 // Initialize inner map for key "vegetables" nestedMap["vegetables"] = make(map[string]int) nestedMap["vegetables"]["carrot"] = 7 nestedMap["vegetables"]["lettuce"] = 2 // Print the nested map fmt.Println(nestedMap) }
Output
map[fruits:map[apple:5 banana:3] vegetables:map[carrot:7 lettuce:2]]
Common Pitfalls
A common mistake is to try assigning values to an inner map before initializing it, which causes a runtime panic because the inner map is nil. Always initialize the inner map with make before adding keys and values.
Wrong way:
nestedMap := make(map[string]map[string]int) nestedMap["fruits"]["apple"] = 5 // panic: assignment to entry in nil map
Right way:
nestedMap["fruits"] = make(map[string]int) nestedMap["fruits"]["apple"] = 5
Quick Reference
- Declare nested map:
map[KeyType]map[InnerKeyType]ValueType - Initialize outer map with
make - Initialize each inner map with
makebefore use - Assign values using
nestedMap[outerKey][innerKey] = value
Key Takeaways
Declare nested maps with map types where values are maps themselves.
Always initialize the outer map using make before use.
Initialize each inner map with make before assigning values to avoid nil map errors.
Assign values by first ensuring inner maps exist for the outer keys.
Print nested maps directly to see their structure in Go.