I am learning to use the map of maps. In the following example, there are three nested maps.
package main
import (
"fmt"
)
func main() {
var data = map[string]map[string]map[string]string{}
data["Date_1"] = map[string]map[string]string{}
data["Date_1"] = make(map[string]map[string]string, 1)
data["Date_1"] = make(map[string]map[string]string, 0)
data["Date_1"]["Sistem_A"] = map[string]string{}
data["Date_1"]["Sistem_A"] = make(map[string]string, 0)
data["Date_1"]["Sistem_A"] = make(map[string]string, 0)
data["Date_1"]["Sistem_A"]["command_1"] = "white"
data["Date_1"]["Sistem_A"]["command_2"] = "blue"
data["Date_1"]["Sistem_A"]["command_3"] = "red"
fmt.Println("data: ", data)
}
Output
data: map[Date_1:map[Sistem_A:map[command_1:white command_2:blue command_3:red]]]
The problem is that if I want to add the values in one step I get a panic: assignment to entry in nil map.
package main
import (
"fmt"
)
func main() {
var data = map[string]map[string]map[string]string{}
data["Date_1"] = map[string]map[string]string{}
data["Date_1"] = make(map[string]map[string]string, 0)
data["Date_1"] = make(map[string]map[string]string, 0)
data["Date_1"]["Sistem_A"] = map[string]string{}
data["Date_1"]["Sistem_A"] = make(map[string]string, 0)
data["Date_1"]["Sistem_A"] = make(map[string]string, 0)
data["Date_1"]["Sistem_A"]["command_1"] = "white"
data["Date_1"]["Sistem_A"]["command_2"] = "blue"
data["Date_1"]["Sistem_A"]["command_3"] = "red"
data["Date_2"]["Sistem_A"]["command_5"] = "violet"
fmt.Println("data: ", data)
}
Output
panic: assignment to entry in nil map
There is very little guidance information at this point. Could you help me?
Thank you.
To update value for a key in Map in Go language, assign the new value to map[key] using assignment operator. If the key we are updating is already present, then the corresponding value is updated with the new value.
Golang Create Nested MapWe 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. The previous code creates a simple restaurant menu using nested maps. In the first map, we set the data type as an int.
It is here:
data["Date_2"]["Sistem_A"]["command_5"] = "violet"
The expression data["Date_2"]
will return a nil-map. It is never initialized, so looking for the index ["Sistem_A"]
panics. Initialize the map first:
data["Date_2"] = make(map[string]map[string]string)
data["Date_2"]["Sistem_A"] = make(map[string]string)
data["Date_2"]["Sistem_A"]["command_5"] = "violet"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With