Gotcha - a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome [wikipedia].
Slice is actually a struct (holding info about pointer to the underlaying array, it’s lenght, and capacity), but it behaves like a pointer. Because it is just a “view” of some memory area.
Sub-slice modification can cause modification of the original slice:
|
|
|
|
What about append
to create a new slice? Nope that’s a bad idea:
|
|
We can see common pattern here. Even in a modern and memory-safe language there are options to mess with memory and pointers.
There is a good example of another gotcha with slices, realated to garbage collector. Check it out here. In short, when you create a slice, in many cases it would be benificial and safer to create it as a copy:
|
|
Just don’t overdo copying, as memory is not infinite unfortunately ;)
References:
Thu Jun 29, 2023 / 308 words / Golang Programming Gotchas