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:
ChristophBerger: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.
JackOhBlades: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.
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]
