Need help adding map[string]interface{} to a map[string]interface{} in a loop.

agolangf · · 313 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I have the following code:</p> <pre><code>package main import ( &#34;sync&#34; &#34;fmt&#34; ) 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{&#34;one&#34;, &#34;two&#34;, &#34;three&#34;} m := map[string]int{ &#34;one&#34;: 1, &#34;two&#34;: 2, &#34;three&#34;: 3, } for i, t := range test { d[&#34;data&#34;] = map[string]interface{}{ &#34;test&#34; : m[&#34;one&#34;], &#34;more&#34;: 1, t: map[string]interface{}{ &#34;i&#34;:i, }, } } fmt.Println(dataSet.data[&#34;data&#34;].(map[string]interface{})[&#34;two&#34;]) fmt.Println(dataSet.data[&#34;data&#34;]) } </code></pre> <p>I get the following output:</p> <pre><code>&lt;nil&gt; 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[&#34;data&#34;] = map[string]interface{}{ &#34;test&#34; : m[&#34;one&#34;], &#34;more&#34;: 1, t: map[string]interface{}{ &#34;i&#34;:i, }, } fmt.Println(dataSet.data[&#34;data&#34;]) } ... </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

313 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传