Golang的嵌套地图 [英] Nested maps in Golang

查看:96
本文介绍了Golang的嵌套地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

func main() {
    var data = map[string]string{}
    data["a"] = "x"
    data["b"] = "x"
    data["c"] = "x"
    fmt.Println(data)
}

它运行.

func main() {
    var data = map[string][]string{}
    data["a"] = append(data["a"], "x")
    data["b"] = append(data["b"], "x")
    data["c"] = append(data["c"], "x")
    fmt.Println(data)
}

它也可以运行.

func main() {
    var w = map[string]string{}
    var data = map[string]map[string]string{}
    w["w"] = "x"
    data["a"] = w
    data["b"] = w
    data["c"] = w
    fmt.Println(data)
}

它再次运行!

func main() {
    var data = map[string]map[string]string{}
    data["a"]["w"] = "x"
    data["b"]["w"] = "x"
    data["c"]["w"] = "x"
    fmt.Println(data)
}

但是失败了!?

Go中的嵌套地图是否存在问题?还是没有对嵌套地图的多括号支持?

Is there a problem with nested maps in Go? Or is there no multiple bracket support for nested maps?

推荐答案

零值地图类型为nil.尚未初始化.您不能在nil映射中存储值,这是运行时的恐慌.

The zero value for map types is nil. It is not yet initialized. You cannot store values in a nil map, that's a runtime panic.

在最后一个示例中,您初始化了(外部)data映射,但是没有任何条目.当您像data["a"]那样对其进行索引时,由于还没有带有"a"键的条目,因此对其进行索引将返回值类型的零值,该值类型对于地图而言为nil.因此,尝试分配给data["a"]["w"]会导致运行时出现紧急情况.

In your last example you initialize the (outer) data map, but it has no entries. When you index it like data["a"], since there is no entry with "a" key in it yet, indexing it returns the zero value of the value type which is nil for maps. So attempting to assign to data["a"]["w"] is a runtime panic.

您必须先初始化地图,然后才能在其中存储元素,例如:

You have to initialize a map first before storing elements in it, for example:

var data = map[string]map[string]string{}

data["a"] = map[string]string{}
data["b"] = make(map[string]string)
data["c"] = make(map[string]string)

data["a"]["w"] = "x"
data["b"]["w"] = "x"
data["c"]["w"] = "x"
fmt.Println(data)

输出(在转到游乐场上尝试):

map[a:map[w:x] b:map[w:x] c:map[w:x]]

请注意,当您声明地图类型的变量并使用复合文字(就像var data = map[string]string{}中一样),也算作初始化.

Note that when you declare a variable of map type and initialize it with a composite literal (as in var data = map[string]string{}), that also counts as initializing.

请注意,您还可以使用复合文字来初始化嵌套地图:

Note that you may also initialize your nested maps with a composite literal:

var data = map[string]map[string]string{
    "a": map[string]string{},
    "b": map[string]string{},
    "c": map[string]string{},
}

data["a"]["w"] = "x"
data["b"]["w"] = "x"
data["c"]["w"] = "x"
fmt.Println(data)

输出是相同的.在去游乐场上尝试.

Output is the same. Try it on the Go Playground.

这篇关于Golang的嵌套地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆