Es Printing A Slice Show Different Values
Fast recall
Quick revision
Core answer
Practical understanding of Slice Internals Len Cap.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
This is the single most common Go data bug, and it's always the same mechanism. t := s[:2] creates a new header pointing at the same array — len 2, cap still 3, so there's a spare slot. append(t, 42) has capacity available, so it takes the in-place path: write 42 at index 2, bump t's len to 3.
Index 2 of the backing array is s's third element. s still has len 3, so when you print it, the runtime shows the array — which now contains 42. You never called append on s, never assigned s anywhere — but s changed, because s was never a copy. It was a window, and the write happened through another window onto the same room.
The fix when this is unwanted: give t its own storage before appending — t := make([]T, len, cap); copy(t, s[:2]), or the idiom append([]T(nil), s[:2]...) — so append's growth-or-in-place decision happens on t's own array, not s's.
Es Printing A Slice Show Different Values
Direct Answer
Because a sub-slice shares the backing array. t := s[:2]; append(t, 42) writes 42 into the third slot of the SAME array — s sees [1 2 42] even though you never touched s directly.
Deep Dive & Architecture
The step-by-step trace makes it permanent:
s := []int{1, 2, 3}
t := s[:2]
// backing: [1 2 3]
// s: ptr→0, len 3, cap 3
// t: ptr→0, len 2, cap 3 ← same array, shorter window
t = append(t, 42)
// len 2 < cap 3 → in-place: backing[2] = 42
// t: ptr→0, len 3, cap 3
// backing is now [1 2 42]
fmt.Println(s) // [1 2 42] ← s's len-3 window over the mutated array
The sub-slice's cap reaching beyond its len is what makes this possible — the runtime allows appending up to cap without reallocating, and cap extends to the end of the underlying array, not to the sub-slice's cut-off point.
This is the mechanism at the center of Go's most famous aliasing bug reports: two views over one array, one grows in place, the other observes the write. Understanding this one trace — and knowing the make+copy escape hatch — is the practical difference between using slices and being surprised by them.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Slice Internals Len Cap, and when would you use it?
- When would you use Slice Internals Len Cap in a real project?
- What is a common mistake when using Slice Internals Len Cap?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.