Go Developer interview question
How do Go slices work?
A Go slice is a small descriptor containing a pointer to a backing array, a length, and a capacity. It is not the array itself, so two slices can share the same underlying storage and observe each other’s element changes.
Direct answer
What a strong answer covers
How it works
Slicing an array or slice creates a new descriptor over the same backing array. append reuses that array while capacity remains; once capacity is exceeded, Go allocates a new array, copies the elements, and the two slices stop sharing memory. Capacity therefore decides whether a write is visible elsewhere, which is why an answer that mentions only length is incomplete.
Example
If a := []int{1, 2, 3, 4} and b := a[:2], then b[0] = 9 also changes a[0]. But appending enough elements to b may allocate a new backing array, after which further writes no longer affect a. Passing a slice to a function copies the header, not the elements, so the callee can mutate shared elements but cannot grow the caller’s slice.
Common mistakes
- Assuming every append creates an independent copy.
- Returning a subslice of a huge buffer and accidentally retaining the whole backing array.
- Appending inside a function and expecting the caller to see the new length.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.