3 ms·
Can you explain this in more detail? I've never used this construct, but I was unaware of its consequences. You've piqued my interest.
by Denzel 9y ago
Can you explain this in more detail?
I've never used this construct, but I was unaware of its consequences. You've piqued my interest.
- Everlag 9y agoThey may be referring to the idea that the result of that operation is defined based on the y's capacity, cap(y). (Capacity is the total amount of space in the slice backing y whereas length is the number of entries used in y; append will not allocate until the new length > capacity) If the capacity is less than the new length, a new backing array will be be allocated. This results in x != y However, if the capacity is sufficient to contain the new values then x == y. Normal usage of append is overwriting the initial slice variable so you don't need to worry about this, x = append(x, ...). If you use two variables, as here, you can potentially have two different slices used as though they were equivalent in later code.
- mappu 9y agoExactly. The inadvertent aliasing can produce situations like this: https://play.golang.org/p/XUtyQ6ShYaz https://play.golang.org/p/XUtyQ6ShYaz , or more plausibly: https://play.golang.org/p/Xx8lZWVWgIu https://play.golang.org/p/Xx8lZWVWgIu
- innagadadavida 9y agoThanks for this. It gets weirder! The slice grows/doubles if capacity is insufficient. So if you initialize the original slice all the way to capacity (len=4, cap=4), it works correctly. But if len=3 and cap=4, it shows bad behavior. https://play.golang.org/p/qf3lAoin4dM https://play.golang.org/p/qf3lAoin4dM
- Denzel 9y agoThank you, to both of you, for the explanation.