我有以下代码:
package main
import (
"sync"
"fmt"
)
var dataSet = struct {
sync.RWMutex
data map[string]interface{}
}{data: make(map[string]interface{})}
func main() {
dataSet.Lock()
defer dataSet.Unlock()
d := dataSet.data
test := []string{"one", "two", "three"}
m := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
for _, t := range test {
d["data"] = map[string]interface{}{
"test" : m["one"],
"more": 1,
t: map[string]int{
"lvl2": 2,
},
}
}
fmt.Println(dataSet.data["data"])
}
这可能吗?
感谢您的帮助,我更新了上述代码。 我对golang很新,其中一些嵌套地图令人困惑。
fmt.Println(dataSet.data["data"])
返回
map[test:1 more:1 three:map[lvl2:2]]
如何让它成为所有3张地图?
fmt.Println(dataSet.data["data"].(map[string]interface{})["three"]
返回
map[lvl2:2]
但
fmt.Println(dataSet.data["data"].(map[string]interface{})["three"]
返回
<nil>
如何附加测试中的所有项目?
谢谢大家!
最终解决方案:https://play.golang.org/p/bRZXye649fY
package main
import (
"fmt"
"sync"
)
var dataSet = struct {
sync.RWMutex
data map[string]interface{}
}{data: make(map[string]interface{})}
func main() {
dataSet.Lock()
defer dataSet.Unlock()
d := dataSet.data
test := []string{"one", "two", "three"}
m := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
for i, t := range test {
dt := map[string]interface{}{
"test": m["one"],
"more": 1,
t: map[string]interface{}{
"i": i,
},
}
// If not set, just use it
if d["data"] == nil {
d["data"] = dt
continue
}
// Otherwise we want to merge new data in
dm := d["data"].(map[string]interface{})
for k, v := range dt {
dm[k] = v
}
}
fmt.Println(dataSet.data["data"].(map[string]interface{})["two"])
fmt.Println(dataSet.data["data"])
}