<p>I have the following code:</p>
<pre><code>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 i, t := range test {
d["data"] = map[string]interface{}{
"test" : m["one"],
"more": 1,
t: map[string]interface{}{
"i":i,
},
}
}
fmt.Println(dataSet.data["data"].(map[string]interface{})["two"])
fmt.Println(dataSet.data["data"])
}
</code></pre>
<p>I get the following output:</p>
<pre><code><nil>
map[test:1 more:1 three:map[i:2]]
</code></pre>
<p>I want the following:</p>
<pre><code>map[i:1]
map[test:1 more:1 two:map[i:1] three:map[i:2]]
</code></pre>
<p>Order in the second line of output will obviously not be in order, but I think everything else is clear. If I print the output inside the loop:</p>
<pre><code>...
for i, t := range test {
d["data"] = map[string]interface{}{
"test" : m["one"],
"more": 1,
t: map[string]interface{}{
"i":i,
},
}
fmt.Println(dataSet.data["data"])
}
...
</code></pre>
<p>I get the data I would expect:</p>
<pre><code>map[one:map[i:0] test:1 more:1]
map[test:1 more:1 two:map[i:1]]
map[test:1 more:1 three:map[i:2]]
</code></pre>
<p>So it seems that t is not appending data rather overwriting it with each loop.</p>
<hr/>**评论:**<br/><br/>nevyn: <pre><p>You need to merge the data in, you are just setting a new value to the same map entry each time through the loop:</p>
<p><a href="https://play.golang.org/p/bRZXye649fY" rel="nofollow">https://play.golang.org/p/bRZXye649fY</a></p></pre>caboose0013: <pre><p>Thanks! That worked perfectly.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传