Nested maps in Golang

Viewed 90648
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?

4 Answers

While the most straightforward answer to this question is to initialize your nested maps as previously described, there is another potential option depending on your access pattern. If you need a truly hierarchical system of maps, then the previous answers are just fine. However, if you simply need to look up values in the map using multiple facets, read on!

It is totally acceptable for maps to use structs as keys (in fact, anything that is comparable can be used). Thus, you can use a single map with struct keys like this example from the Golang blog, which is a hit counter that tracks page hits by country:

type Key struct {
  Path, Country string
}

hits := make(map[Key]int)

// set: Vietnamese person visiting the home page
hits[Key{"/", "vn"}]++

// get: see how many Chinese persons read the spec
n := hits[Key{"/ref/spec", "cn"}]

I don't see maps like this often enough, instead many people reach for the nested variant first, which I think may not always be the right fit.

In addition to icza's answer. Map initialization can be written in short form:

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

Output is the same. Try it on the Go Playground. The key "d" added to demonstrate the mapping with an empty map.

The below solution might be useful for you.

var data = map[string]interface{}{
        "publishInfo": map[string]interface{}{
            "title":       publishInfo.Title,
            "description": publishInfo.Desc,
            "thumbnail":   publishInfo.ImageSrc,
            "url":         publishInfo.URL,
            "tags":        publishInfo.Tags,
        },
        "revision": draftInfo.Revision,
    }
Related