What does this print? (two appends on the same base slice)
Question 43HardGo 1.22 to 1.25
x := make([]int, 0, 5)
x = append(x, 1, 2, 3)
y := append(x, 4)
z := append(x, 5)
fmt.Println(x, y, z)
Output: [1 2 3] [1 2 3 5] [1 2 3 5]
x has len 3 and cap 5. Both appends fit in the spare capacity, so both write to index 3 of the same backing array. y and z are two headers (len 4) over the same memory. The second append overwrites the first, and y "changes" without anyone touching it.
This is the classic aliasing bug. It often shows up in recursive backtracking (for example, building subsets or permutations with append(path, v)) and in code that builds several slices from a shared prefix.
// Fix 1: copy explicitly
y := append(slices.Clone(x), 4)
// Fix 2: cap the base with a full slice expression so append must reallocate
y := append(x[:len(x):len(x)], 4)
z := append(x[:len(x):len(x)], 5)
Interviewer signal: can you explain it in terms of the header and capacity, and do you know the three-index fix?
More on Arrays, Slices, Maps & Strings
- Q41What does this program print? (append inside a function with spare capacity)
- Q42How does append grow a slice? Why is the resulting capacity sometimes not exactly double?
- Q44What is the full slice expression a[low:high:max], and when would you use it?
- Q45What is the difference between a nil slice and an empty slice? When does it matter?
- Q46Explain the semantics of the built-in copy. Is it safe with overlapping slices?
- Q47How do arrays differ from slices? Can you convert between them?