Nested Maps
Nested Maps are those in which values in key:value pairs of the outer map are also maps. In other words maps inside a map, hence nested maps.
In this tutorial, we will learn how to create nested maps in Go language, with the help of example programs.
Create Nested Map
Similar to how we declare the type of key and value while defining a map, since values are also maps, to define a map x
with keys of string type, and values of type map[string]string, use the following code.
</>
Copy
var x = map[string]map[string]string{}
Example
In the following example, we will define a nested map, and initialize it with some values.
example.go
</>
Copy
package main
import (
"fmt"
)
func main() {
var x = map[string]map[string]string{}
x["fruits"] = map[string]string{}
x["colors"] = map[string]string{}
x["fruits"]["a"] = "apple"
x["fruits"]["b"] = "banana"
x["colors"]["r"] = "red"
x["colors"]["b"] = "blue"
fmt.Println(x)
}
Output
map[colors:map[b:blue r:red] fruits:map[a:apple b:banana]]
Conclude
In this Golang Tutorial, we learned what a nested map is, and how to create it with examples.