The user with no hat
The user with no hat

Reputation: 10846

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 [] .

Upvotes: 24

Views: 86906

Answers (1)

nemo
nemo

Reputation: 57599

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
}

Upvotes: 27

Related Questions