Re Len And Cap Of A Slice
Fast recall
Quick revision
Core answer
Whether you understand Slice Internals Len Cap 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
A slice is a header with three fields: a pointer to the start of its elements, a length, and a capacity. The length is what you iterate over — for i := 0; i < len(s); i++ and what range covers. The capacity is the size of the underlying array from the slice's start — the total room the slice can grow into before the runtime has to move it.
They differ the moment you re-slice: t := s[:2] on a 3-element slice gives len 2 but cap 3, because the backing array still has that third slot. That gap is exactly what append exploits — appending to t writes into the spare slot in place.
When len reaches cap, the next append allocates a new, larger backing array (roughly double for small slices), copies the elements, and the slice header now points at the new storage. Old aliases to the previous array don't see the growth — they've forked.
Re Len And Cap Of A Slice
Direct Answer
len is how many elements the slice can see right now; cap is how many slots exist in the backing array. Appends below cap never allocate; at cap, append reallocates and roughly doubles.
Deep Dive & Architecture
The len/cap split exists because slices are windows over arrays, not owned storage. The backing array is a fixed-size allocation; the slice header is a lens over it:
s := make([]int, 2, 4)
backing array: [ _ _ _ _ ] (4 slots allocated)
s: ptr ──▶ [ 0 0 ] len 2 — what s can see
cap 4 — total room from ptr
Every slice operation is defined on these two numbers. Indexing checks against len (index 2 of len-2 slice panics even though slot 2 physically exists). Append checks against cap. Re-slicing recomputes both within the cap budget: s[2:4] on a cap-4 slice is legal even for a len-2 slice, because the window arithmetic works on the underlying array's extent.
This is also why cap is a performance property and len is a correctness property: exceeding len is a bug the runtime catches (panic); exceeding cap is just an allocation the runtime handles. Code that pre-sizes with make([]T, 0, n) is aligning cap with the expected len so the appends never pay the copy.
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 Slice Internals Len Cap in a real project?
- How would you compare Slice Internals Len Cap with an alternative?
- 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.