Go Slice Gotcha
Go is, mostly, a straightforward and unsurprising language.
One thing that caught me recently was the behavior of slices.
The setup
A slice and a subslice; no surprises yet.
What are the consequences of this append
? Spoilers ahead!
Oh no…
chunk
contains what you would expect.
What about that 999
after 8 in the original slice?!
Slice Capacity
The answer is not the len
, check the cap
Why 9? Because the extra capacity of the original slice was carried over when slicing. There were 9 elements from index 3 to the end of the slice:
The Solution
Go has a syntax to limit the cap
when subslicing:
It’s worth reading Slice expressions; especially the “Full slice expressions” subsection.
a[low : high : max]
I found that Go in Action (section 4.2.3) had a great explanation on this:
The purpose [of the third index] is not to increase capacity, but to restrict the capacity.
You’re still sharing the underlying array, within the valid indices. If you try to append, it’s a copy on write.
Conclusion
I’m just surprised this syntax doesn’t work the other way around:
Ugly? Yes. But I like syntactic vinegar when doing things that aren’t straightforward.