Common Slice Gotchas in Go

Shared Backing Arrays and Memory Leaks

Fix Go slice memory leaks by always assigning the return value of functions like slices.Delete to update the slice header.

Shared backing arrays cause memory leaks when slice functions like slices.Delete or slices.Compact leave old pointers in the underlying array beyond the new length. Always assign the return value of these functions to update the slice header and ensure the garbage collector can reclaim the memory.

s = slices.Delete(s, 2, 5)

Ignoring the return value leaves the original slice pointing to the modified array with stale pointers, preventing garbage collection of the deleted elements.