data structures - How can I write an array of maps [golang] -
i have map has value 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 out how go
seems allow setting data @ 1 level when deal maps [name][value] = value
.
so far have code fails
package main func main() { := []string{"coins", "notes", "gold?", "coins", "notes"} thismap := make(map[string][]map[string]int) k, v := range { amap := map[string]string{ "random": "something", } thismap[v] = [k]amap } }
edit: slice values ("coins", "notes" etc ) can repeat reason why need use index []
.
working example (click play):
something := []string{"coins", "notes", "gold?"} thismap := make(map[string][]map[string]int) _, v := range { amap := map[string]int{ "random": 12, } thismap[v] = append(thismap[v], amap) }
when iterating on newly created thismap
, need make room new value amap
. builtin function append
when using slices. makes room , appends value slice.
if you're using more complex data types can't initialized slices, first have check if key in map and, if not, initialize data type. checking map elements documented here. example maps (click play):
thismap := make(map[string]map[string]int) _, v := range { if _, ok := thismap[v]; !ok { thismap[v] = make(map[string]int) } thismap[v]["random"] = 12 }
Comments
Post a Comment