Slices
Slices are Go's workhorse collection — dynamic views into underlying arrays with length and capacity.
Introduction
Slices are Go's workhorse collection — dynamic views into underlying arrays with length and capacity. The built-in append function grows slices, potentially reallocating. Understanding slice headers (pointer, len, cap) explains aliasing bugs that plague even experienced developers.
Slices power JSON arrays, database result sets, HTTP middleware chains, and buffer management. Mastering slice expressions (s[low:high:max]), copy, and nil vs empty slice distinction is mandatory for production Go and interviews.
This lesson includes Go 1.21+ slices package helpers (Contains, Equal, Compact) that replace hand-rolled loops in modern codebases.
The story
A Google Cloud Load Balancer health-check service maintains a dynamic list of backend endpoints. Slices grow as autoscaler events add pods and shrink when nodes drain — append amortizes allocation while [:0] resets length without freeing capacity, a trick used in high-throughput log aggregators processing millions of events per second.
Understanding slice headers (pointer, length, capacity) explains subtle bugs when sharing subslices across goroutines in a microservice mesh.
Understanding the topic
Key concepts
- Slice header: pointer to array, len, cap — s[i:j] creates sub-slice sharing backing array.
- append(s, elems...) may reallocate if cap exceeded — returns new slice header.
- nil slice vs empty slice: both len 0; nil has no backing array.
- make([]T, len, cap) preallocates; len defaults elements to zero.
- copy(dst, src) copies min(len(dst), len(src)) elements.
- Full slice expression s[low:high:max] limits cap of result slice.
Step-by-step explanation
- Literal: []int{1,2,3} creates slice with backing array.
- append adds elements; if len < cap, uses existing array; else doubles cap.
- Sub-slice shares array — mutation visible across slices.
- Pass slice to function — copies header only, not elements.
- Range gives index and copy of element (struct copy).
- slices.Clone (Go 1.21+) deep-copies slice elements.
Practical code example
Slice growth, sub-slicing, and safe copying:
package mainimport ("fmt""slices")func main() {s := make([]int, 0, 4)s = append(s, 1, 2, 3)fmt.Printf("s=%v len=%d cap=%d\n", s, len(s), cap(s))sub := s[1:3] // shares backing arraysub[0] = 99fmt.Println("after sub mutate:", s)cloned := slices.Clone(s)cloned[0] = 0fmt.Println("original:", s, "clone:", cloned)fmt.Println("contains 99:", slices.Contains(s, 99))}
Output
s=[1 2 3] len=3 cap=4 after sub mutate: [1 99 3] original: [1 99 3] clone: [0 99 3] contains 99: true
Line-by-line code explanation
s := make([]int, 0, 4)creates an int slice with length 0 and capacity 4, so room for four elements is allocated up front.s = append(s, 1, 2, 3)adds three values. They fit in the existing capacity, so no new array is needed, and append returns the updated slice, which is assigned back to s.fmt.Printf("s=%v len=%d cap=%d\n", s, len(s), cap(s))prints the slice contents, the number of elements in it, and how many it can hold before it must grow.sub := s[1:3]takes elements at index 1 and 2 as a new slice. It does not copy; sub shares the same underlying array as s.sub[0] = 99changes the first element of sub, which is the same memory as s[1], so the next Println shows s with the 99 in it.cloned := slices.Clone(s)makes an independent copy of s in a new backing array.cloned[0] = 0changes only the copy, so s keeps its original first element.fmt.Println("original:", s, "clone:", cloned)prints both slices so you can see that they now differ.slices.Contains(s, 99)checks whether any element equals 99; the Println around it prints the true or false result.
Key takeaway: Always consider aliasing when sub-slicing. Use slices.Clone before mutating if independence needed. Preallocate with make when size known.
Real-world use
Where you'll use this in production
- Building response DTO slices from database rows.
- Buffer pooling in high-throughput HTTP servers.
- Batch processing with sliding window sub-slices.
- Collecting errors from parallel workers into []error.
Best practices
- Preallocate: make([]T, 0, expectedSize) when count known.
- Use slices.Clone before mutating shared sub-slices.
- Prefer slices.Contains, Equal, Compact over manual loops.
- Return nil slice for 'no results' — idiomatic; json encodes as [].
- Avoid append in tight loops without prealloc — causes repeated realloc.
- Use full slice expression to prevent accidental cap extension.
Common mistakes
- Appending to slice while ranging over it — undefined behavior.
- Sub-slice aliasing causing unexpected mutations.
- Confusing nil and empty slice in JSON — both encode as [].
- Not checking append return: s = append(s, x) — append may reallocate.
- Holding pointer to slice element across append — invalid after realloc.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionSlice internals?+
Answer
2BeginnerQuestionnil vs empty slice?+
Answer
3IntermediateQuestionappend reallocation behavior?+
Answer
4IntermediateQuestionPrevent sub-slice aliasing bugs?+
Answer
5AdvancedQuestionDesign API returning slice — nil or empty?+
Answer
Summary
Slices are dynamic views with pointer, len, and cap. append may reallocate — always assign result: s = append(s, x). Sub-slices share backing arrays — clone before independent mutation. Preallocate with make when size is predictable. Next lesson: maps — key-value associative stores.