mediumConceptCodingEntryMidSenior
What happens when you append to a slice, and when do two slices stop sharing memory?
Go slice append either extends the existing backing array or allocates a new one when capacity is exhausted. Bugs appear when two slices share the same array and one append mutates data the other still observes.
5 min readUpdated 2026-08-15
Answer
Short answer
A slice is a view over an array with length and capacity. append may reuse that array or allocate a new one, so code that keeps aliases to related slices must treat append as a possible shared-memory mutation.
Was this answer helpful?
Likely follow-ups
- Why must you always assign the result of append back to a variable?
- You pass a slice to a function and it appends to it. Why does the caller sometimes see the change and sometimes not?
- How would you delete an element from the middle of a slice without leaking the pointer it held?
- What does copy return, and how does it behave when the two slices overlap?
Related questions
- A hot path allocates heavily and garbage collection is showing up in your profile. What does Span give you that a substring does not?hardAlso on memory and garbage-collection4 min
- Memory keeps climbing in a Go service under load. How do you find out why, and what can you actually tune?hardAlso on garbage-collection and memory6 min
- A long-running Python service keeps climbing in memory and never comes back down. How do you work out where the memory went?hardAlso on memory and garbage-collection5 min
- How does the .NET garbage collector decide what to collect, and how would you make a hot path allocate less?hardAlso on garbage-collection and memory6 min