confusion about append() built in

blov · 2018-03-14 14:30:11 · 689 次点击    
这是一个分享于 2018-03-14 14:30:11 的资源,其中的信息可能已经有所发展或是发生改变。

func append(slice []Type, elems ...Type) []Type

Does append ever update slice? or create a new one and copy and then return?

on the same track,

var slice = oldslice and copy(slice, oldslice) as slice is similar to pointer, I am not sure the difference


评论:

hobbified:

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.

ChristophBerger:

I wrote an article about slices (https://appliedgo.net/slices/) that includes a visualization of the append operation, hope that helps.

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.

JackOhBlades:

An interesting note: append 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:

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]

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

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