"If the capacity of s is not large enough to fit the additional values, 
append allocates a new, sufficiently large underlying array that fits both 
the existing slice elements and the additional values. Otherwise, append 
re-uses the underlying array."

That seems pretty explicit to me? That's from the spec, the other link 
above, the blog, is even more explicit, by straight up showing the 
implementation before introducing the built-in. 

The tour also says it: https://tour.golang.org/moretypes/15 
"If the backing array of s is too small to fit all the given values a 
bigger array will be allocated. The returned slice will point to the newly 
allocated array."

It also links to this documentation: https://blog.golang.org/slices-intro 
"The append function appends the elements x to the end of the slice s, and 
grows the slice if a greater capacity is needed." - this is the only one 
that seems less than explicit about the semantics, and in the sense that it 
does not make explicit that 'grows the slice' means 'returns a copy of the 
slice with greater capacity.' 

The latter link then links further to this documentation: 
and just like the blog, it starts by introducing the implementation, where 
it is clear that only one path includes a copy function, and it explicitly 
says "If the data exceeds the capacity, the slice is reallocated." A bit 
later where it covers append directly, it says "The result needs to be 
returned because, as with our hand-written Append, the underlying array may 

4 bits of official documentation, all of which mention the 'gotcha' more or 
less directly. And in most of those cases, discussion of append directly 
follows discussion of 'copy', which should make it clear how to get copies 
of slices.

I think maybe where it gets missed is from people learning the language by 
example, by coping code from StackOverflow, reading code in GitHub, etc. Go 
is pretty surprisingly easy to pick up by example like that, but it does 
mean those corner cases can bite - however, the actual documentation is 
pretty clear and up-front about the gotchas.

You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 

Reply via email to