Back to questions
MiddleTheoryOccasional
What pitfalls do Go slices have because of the shared backing array?
Slices share a backing array, so three pitfalls follow. Writing through one slice mutates others where ranges overlap. append may or may not touch the original, depending on spare capacity. And a small sub-slice keeps the whole large array alive, blocking GC. Mitigate with copy or s[low:high:max].
- Believing a sub-slice is an independent copy — it aliases the parent's backing array
- Assuming
appendalways reallocates — within sparecapit overwrites shared elements - Overlooking memory retention — a tiny sub-slice can pin a huge array in memory
- How does a three-index slice
s[low:high:max]prevent the aliasing on the nextappend? - Why can a small sub-slice of a large array cause a memory leak, and how do you fix it?
</content>