How can I write an array of maps [golang]

I have a map that has an array of maps as its value.

Example:

thisMap["coins"][0] = aMap["random":"something"] thisMap["notes"][1] = aMap["not-random":"something else"] thisMap["coins"][2] = aMap["not-random":"something else"] 

I can't figure out how to do this, since go seems to only allow data to be set at one level when dealing with maps [name][value] = value .

So far I have this code that fails

 package main func main() { something := []string{"coins", "notes", "gold?", "coins", "notes"} thisMap := make(map[string][]map[string]int) for k, v := range something { aMap := map[string]string{ "random": "something", } thisMap[v] = [k]aMap } } 

Change The slice values ​​("coins", "notes", etc.) can be repeated, so for this I need the index [] .

+8
arrays data-structures go
source share
1 answer

Working example ( click to play ):

 something := []string{"coins", "notes", "gold?"} thisMap := make(map[string][]map[string]int) for _, v := range something { aMap := map[string]int{ "random": 12, } thisMap[v] = append(thisMap[v], aMap) } 

When repeating the newly created thisMap you need to make room for the new aMap value. The built-in append function does this for you when using slices. This makes the room and adds value to the slice.

If you use more complex data types that cannot be initialized as easily as slices, you first need to check if the key is on the map, and if not, initialize your data type. Checking map elements is documented here . An example with maps ( click to play ):

 thisMap := make(map[string]map[string]int) for _, v := range something { if _, ok := thisMap[v]; !ok { thisMap[v] = make(map[string]int) } thisMap[v]["random"] = 12 } 
+10
source share

All Articles