dsfsdf7852 2017-06-01 10:53 采纳率: 100%
浏览 40
已采纳

Golang的嵌套地图

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

It runs.

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)
}

It also runs.

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)
}

It runs again!

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

But it fails!?

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

  • 写回答

3条回答 默认 最新

  • duanhuan2301 2017-06-01 10:57
    关注

    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.

    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)
    

    Output (try it on the Go Playground):

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?