What does append(a[:1], 99) print for a and b?
Determine the two printed slices and explain whether a and b share a backing array.
a := []int{1, 2, 3}
b := append(a[:1], 99)
fmt.Println(a, b)
Predict the output.
It prints [1 99 3] [1 99]. a[:1] has len 1 but cap 3, so append has spare capacity and writes 99 into the same backing array at index 1, overwriting a[1]. Both slices view that array. Force a copy with the full-slice expression a[:1:1] so append reallocates.
- ✗Assuming
appendalways returns a fresh array — it reuses the backing array whenevercap > len - ✗Confusing
lenwithcap—a[:1]haslen 1but inheritscap 3froma - ✗Forgetting the full-slice expression
a[:1:1]caps capacity to force a reallocation
- →How does
a[:1:1]change the capacity, and why does that prevent the aliasing? - →If two
appendcalls share one base slice with sparecap, why does the second overwrite the first?
What does this code print?
a := []int{1, 2, 3}
b := append(a[:1], 99)
fmt.Println(a, b)
Output
[1 99 3] [1 99]
Why the slices share memory
a[:1] takes the first element of a but inherits the capacity of the original slice: len 1, cap 3.
append has spare room (len 1 < cap 3), so it does not reallocate — it writes 99 into the same backing array at index 1. That overwrites a[1] (was 2), making a become [1 99 3]. The returned b has len 2: [1 99].
⚠️ This is a classic trap: a "harmless" append silently corrupts a neighbouring slice that shares the backing array. The same bug appears when one base slice with spare cap is appended to twice — the second append overwrites the first.
The fix is the full-slice expression a[:1:1] (low:high:max), which sets cap == len, so the next append must allocate a new array:
b := append(a[:1:1], 99) // cap=1 → append reallocates, a untouched
// a == [1 2 3], b == [1 99]