我正在学习使用映射图。在下面的例子中,有三个嵌套的映射。
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)
}
输出
data: map[Date_1:map[Sistem_A:map[command_1:white command_2:blue command_3:red]]]
问题在于,如果我想一步添加值,会出现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)
}
输出
panic: assignment to entry in nil map
此时,指导信息非常有限。你能帮助我吗?
谢谢。
data
已初始化。地图data["someitem"]
未初始化。 - Burak Serdar