Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write an array of maps [golang]

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

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 it out how to do this as go seems to allow setting data only at one level when you deal with maps [name][value] = value.

So far I have this code which 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
    }
}

Edit: The slice values ("coins", "notes" etc ) can repeat so this is the reason why I need use an index [] .

like image 932
The user with no hat Avatar asked Apr 14 '14 17:04

The user with no hat


People also ask

Can we use array in map?

. map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.


1 Answers

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 iterating over the newly created thisMap, you need to make room for the new value aMap. The builtin function append does that for you when using slices. It makes room and appends the value to the slice.

If you're using more complex data types that can't be initialized as easily as slices, you first have to check if the key is already in the map and, if it is not, initialize your data type. Checking for map elements is documented here. 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
}
like image 136
nemo Avatar answered Sep 19 '22 18:09

nemo