我有一个地图,其值为一组地图.
例:
thisMap["coins"][0] = aMap["random":"something"] thisMap["notes"][1] = aMap["not-random":"something else"] thisMap["coins"][2] = aMap["not-random":"something else"]
我无法弄清楚如何做到这一点似乎只允许在处理maps [name] [value] = value时在一个级别设置数据.
到目前为止,我的代码失败了
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 } }
编辑:切片值(“硬币”,“注释”等)可以重复,所以这就是我需要使用索引[]的原因.
工作实例(
click to play):
原文链接:https://www.f2er.com/go/186919.htmlsomething := []string{"coins","gold?"} thisMap := make(map[string][]map[string]int) for _,v := range something { aMap := map[string]int{ "random": 12,} thisMap[v] = append(thisMap[v],aMap) }
迭代新创建的thisMap时,需要为新值aMap腾出空间.内置函数append在使用切片时为您执行此操作.它腾出空间并将值附加到切片上.
如果您正在使用无法像切片一样轻松初始化的更复杂的数据类型,则首先必须检查密钥是否已在映射中,如果不是,则初始化数据类型. here记录了检查地图元素.地图示例(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 }