Why does append() modify the provided slice? (See example)

See http://blog.golang.org/go-slices-usage-and-internals.

The append function could allocate a new underlying array if what you are appending to the slice does not fit in the current slice’s capacity. Append does modify the underlying array. The reason you have to assign back to the variable is because, as I said in the first sentence, the underlying array could be reallocated and the old slice will still point to the old array.

See this play example to see exactly what I am talking about.

Leave a Comment