Appending to array in a for loop?

blov · · 518 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;ve got the following code:</p> <pre><code>for _, e := range events { //Get all the items for this event. items, err := getBidItemsForEvent(e.Event.Event_ID) fmt.Printf(&#34;%#v\n\n&#34;, items) if err != nil { fmt.Println(&#34;Error at getting item events in GetEventsByUserId&#34;, err.Error()) } //Append them to the events items array. for _, i := range items { e.Items = append(e.Items, i) fmt.Println(i) } } </code></pre> <p>The idea is there&#39;s multiple events with multiple items going in to them. Within the events loop, I get the items from the event. The printf items prints these out (an array of items). The next for loop is supposed to append the item to the original event items array. I can also see the item by printing &#39;i&#39;.</p> <p>What&#39;s returned is a nil array though. Am I missing something on how to append within a for loop?</p> <hr/>**评论:**<br/><br/>natdm: <pre><p>Aha! Solved it..</p> <p>I have to append directly to the slice, not within the for loop.</p> <pre><code>for i, event := range events { //Get all the items for this event. items, err := getBidItemsForEvent(event.Event.Event_ID) fmt.Printf(&#34;%#v\n\n&#34;, items) if err != nil { fmt.Println(&#34;Error at getting item events in GetEventsByUserId&#34;, err.Error()) } //Append them to the events items array. for _, item := range items { events[i].Items = append(events[i].Items, item) } } </code></pre></pre>dchapes: <pre><p>This:</p> <pre><code>for _, item := range items { events[i].Items = append(events[i].Items, item) } </code></pre> <p>is better written as:</p> <pre><code>events[i].Items = append(events[i].Items, items...) </code></pre></pre>natdm: <pre><p>Nice, I didn&#39;t know about that. Thanks!</p></pre>Fwippy: <pre><p><code>e</code> is a copy of the event.</p> <p>Compare: <a href="https://play.golang.org/p/OMdDdz1K32" rel="nofollow">https://play.golang.org/p/OMdDdz1K32</a> (similar to yours) vs <a href="https://play.golang.org/p/ireemFw2Xi" rel="nofollow">https://play.golang.org/p/ireemFw2Xi</a></p></pre>justinisrael: <pre><p>If events were a slice of Event pointers, then I would think it would work fine. If your slice contains value types, then they are copies on each loop and don&#39;t retain your changes when assigning to the Items field </p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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