Ppend() Do In Go, And Why Must
Fast recall
Quick revision
Core answer
Whether you understand Append And Growth beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
Append takes a slice and one or more values, and returns a slice — that return is the contract. Two things can happen inside. If the backing array has spare capacity, the value is written into the next slot and the same header (with len bumped) comes back — no allocation. If the slice is at capacity, append allocates a bigger array, copies everything over, and returns a header pointing at the new storage.
Because you can't know from the call site which happened, the only safe pattern is reassignment. s = append(s, x) works in both cases. Skipping the assignment is a real bug: when growth occurred, the caller keeps the old header — pointing at the old array — and the appended element is invisible. The classic shape is appending in a helper and losing the growth in the caller.
The corollary: append never mutates the header you passed; it returns the up-to-date one. The elements may be shared — in-place writes are visible to aliases — but the header itself is only ever returned, never modified in place.
Ppend() Do In Go, And Why Must
Direct Answer
append returns a possibly-new header: in place if capacity remains, reallocated if not. The header may change, so the caller must reassign: s = append(s, x).
Deep Dive & Architecture
Why is reassignment the only safe pattern? Because the two modes are indistinguishable from the call site:
s := make([]int, 0, 4)
s = append(s, 1) // in-place mode (cap 4 spare)
s = append(s, 2) // in-place mode
newS := append(s, 3) // still in-place, but imagine this was at cap
In the at-cap case, the old s and the returned slice are two different windows onto two different arrays. The runtime didn't update s's header — it can't, the header lives in your variable. So append's return value is the new truth, and the old variable is stale the moment capacity was exceeded.
This is the mechanism behind Go's most-found code review comment (s = append(s, ...) missing). The go vet tool has never flagged it because both modes are legal Go — it's a semantic stale-reference bug, invisible to static checks, which is why the idiom must be muscle memory.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Append And Growth in a real project?
- How would you compare Append And Growth with an alternative?
- What is a common mistake when using Append And Growth?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.