If you are new to Golang Maps, check our tutorial on the topic to learn more. In this guide, we will focus on creating and working with nested maps.
What Is Nested Map?
A nested map is simply a map of maps. This means that the key-value pairs of the outer map are another map.
Golang Create Nested Map
We can define a nested map the same way we declare a normal map. We start by setting the data type of the key (top-level map) and the type of the value. Since this is a nested map, the value of the top-level map is a map.
An example code is as shown below:
func main() {
nested := map[int]map[string]string{
1: {
"a": "Apple",
"b": "Banana",
"c": "Coconut",
},
2: {
"a": "Tea",
"b": "Coffee",
"c": "Milk",
},
3: {
"a": "Italian Food",
"b": "Indian Food",
"c": "Chinese Food",
},
}
}
The previous code creates a simple restaurant menu using nested maps. In the first map, we set the data type as an int. We then declare the value as a type map that contains its key-value pairs of type string.
Golang Print Nested Map
We can print a nested map using the default printing methods. For example, we can use the Println method from the fmt package as shown:
This should return an output as shown:
map[1:map[a:Apple b:Banana c:Coconut] 2:map[a:Tea b:Coffee c:Milk] 3:map[a:Italian Food b:Indian Food c:Chinese Food]]
Golang Iterate Nested Map
We can iterate over a nested map using the for loop and a range operator. An example is provided below:
fmt.Println(k, v)
}
The previous code should return the nested maps as:
2 map[a:Tea b:Coffee c:Milk]
3 map[a:Italian Food b:Indian Food c:Chinese Food]
To iterate over an individual map, we can access it using its key. For example, to iterate over the first nested map (key 1), we can do the following:
fmt.Println(k, v)
}
Golang Delete Nested Map
We can also delete a key-value pair from a nested map using the delete method. The code snippet is as shown:
fmt.Println(nested)
The previous code should access the map with key 1 and remove the key “a” from the resulting dictionary.
An example resulting output is provided below:
Note: the key “a” has been removed from the first nested map.
Conclusion
This guide illustrated how to work with nested maps or map of maps. Using this article, you learned how to create a nested map, iterate over a nested loop, and insert and remove elements from a nested map. We hope you found this article helpful. Check out other Linux Hint articles for more tips and tutorials.