gotchagoMajor
Go slice append gotcha — shared underlying array
Viewed 0 times
slice appendshared arrayfull slice expressioncopy slicecapacitysub-slice
Error Messages
Problem
Appending to a Go slice derived from another slice (via slicing) unexpectedly modifies the original slice. Or changes to the original appear in the derived slice.
Solution
Go slices share the underlying array when derived via slicing (s2 := s1[1:3]). Appending to s2 may overwrite s1's elements if capacity allows. Fixes: (1) Use full slice expression to limit capacity: s2 := s1[1:3:3]. (2) Copy explicitly: s2 := make([]T, len(s1[1:3])); copy(s2, s1[1:3]). (3) Use append to create a new slice: s2 := append([]T(nil), s1[1:3]...). Rule: if you're passing a sub-slice to code that might modify it, always copy.
Why
Go slices are (pointer, length, capacity) tuples. Sub-slicing shares the pointer. Append only allocates a new array when length == capacity, otherwise it writes into the shared backing array.
Revisions (0)
No revisions yet.