> On Jun 26, 2020, at 9:28 AM, Robert Engels <reng...@ix.netcom.com> wrote:
> 
>> On Jun 26, 2020, at 8:23 AM, David Riley <fraveyd...@gmail.com> wrote:
>> 
>> You are correct, the programmer needs to read the manual. Slices are 
>> "windows" into their underlying array, therefore assigning data into slices 
>> tied to a given array changes the data in other arrays as well.  The 
>> append() function merely extends the slice by n and assigns into those 
>> elements, returning the new slice header (the old one can remain unchanged, 
>> but they will both be slices of the same array).
>> 
>> Ian pointed to the canonical documentation on this: 
>> https://blog.golang.org/slices
>> 
>> Additionally, the language spec has this: 
>> https://golang.org/ref/spec#Appending_and_copying_slices
>> 
>> I do agree that it would be nicer if this were flagged a little more loudly, 
>> since the semantics of the append() builtin can lead the early developer to 
>> believe they are making a copy of the slice in question, but they aren't.
>> 
> That is not quite true. Once is it extended beyond the current capacity you 
> will have a new backing array and the slices will diverge.

Agreed, but the problem here is that unless you are checking the capacity 
beforehand, you cannot count on that behavior.  The general point is that if 
you want a modified copy of an array/slice, you need to be explicit about it or 
you will run into unpredictable and unpleasant to debug problems, but that is 
not immediately apparent given the superficial semantics of the append() 
builtin unless you understand slices at a deeper level.

As in all things, the proper fix is to RTFM, but I think TFM could afford to be 
a *tiny* bit more explicit about this because it's surprisingly easy to miss.


- Dave



-- 
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 
https://groups.google.com/d/msgid/golang-nuts/222003D0-79C2-46D8-B0CE-41CF0342BE78%40gmail.com.

Reply via email to