Hi Henry,

On Mon, Jun 27, 2016 at 3:55 AM, Henry <henry.adisuma...@gmail.com> wrote:
> If you were to change the code a bit as follows 
> https://play.golang.org/p/VwtWRQBrEe , it will work as you expect.
>
> I think it is probably safer to instantiate a slice without specifying the 
> initial capacity.

Having the capacity larger than the number of used elements (the
length of the slice) is indeed the problem. However, not specifying
the capacity can also fail you. Here I changed the numbers of elements
appended slightly and print the capacity after each operation:

  https://play.golang.org/p/WBTRvgJJKW

As you can see, append will over-allocate and set the capacity of the
underlying array to 4 when we go from an empty slice to a slice with
length 3. This in turn makes the following appends to a and b share
the 4th slot in the array and appending to a will ultimately update
the value you see in b.

In your example you were "lucky" since you started with a = [1, 2] and
cap(a) = 2. When you create b, append notices that the capacity is
exhausted and *creates a new underlying array for b*. After that step,
a and b are no longer "entangled" like this and updates to one cannot
affect the other.

-- 
Martin Geisler

-- 
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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to