confusion about append() built in

blov · · 484 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>func append(slice []Type, elems ...Type) []Type</p> <p>Does append ever update slice? or create a new one and copy and then return?</p> <p>on the same track, </p> <p>var slice = oldslice and copy(slice, oldslice) as slice is similar to pointer, I am not sure the difference</p> <hr/>**评论:**<br/><br/>hobbified: <pre><p>Either, depending on whether or not it&#39;s able to grow in place. Don&#39;t count on it always being different, and don&#39;t count on it always being the same.</p></pre>ChristophBerger: <pre><p>I wrote an article about slices (<a href="https://appliedgo.net/slices/" rel="nofollow">https://appliedgo.net/slices/</a>) that includes a visualization of the append operation, hope that helps. </p> <p>TL;DR: append updates the slice as long as the underlying array has some space left. Else it allocates a new, longer array. If you want to avoid or minimize copying and allocation, make the initial capacity large enough.</p></pre>JackOhBlades: <pre><p>An interesting note: <code>append</code> modifies the slice header, which means the underlying array might share the same data, but the new value is a distinct slice value. This means you can do this: </p> <pre><code>first := []string{&#34;foo&#34;, &#34;bar&#34;, &#34;baz&#34;} second := append(first, &#34;foobar&#34;) fmt.Printf(&#34;%v\n&#34;, first) // [foo, bar, baz] fmt.Printf(&#34;%v\n&#34;, second) // [foo, bar, baz, foobar] </code></pre></pre>

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

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