Go

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

All 37 Arrays, Slices, Maps & Strings questions