<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's able to grow in place. Don't count on it always being different, and don'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{"foo", "bar", "baz"}
second := append(first, "foobar")
fmt.Printf("%v\n", first) // [foo, bar, baz]
fmt.Printf("%v\n", second) // [foo, bar, baz, foobar]
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传