Python Arrays vs Slices: Dynamic Memory & Headers
In Go, fixed arrays are values, while slices are lightweight windows (slice headers containing pointer, len, cap) pointing to backing arrays. Learn append semantics, capacity doubling, and reallocations.
"Think of an array as a concrete driveway of fixed length. A slice is a portable frame you place over any portion of that driveway. Moving or resizing the frame is instant because the concrete stays in place."
Deep Dive: How It Works
Array vs Slice: An array [5]int has fixed size; a slice []int is a 3-word header (data pointer, length, capacity).
Append Mechanics: When append exceeds capacity, Go allocates a larger backing array, copies data, and updates the header.
Sub-slicing: s[low:high] creates a new slice header referencing the same underlying backing array.
Syntax Blueprint
s := make([]int, 0, 4) s = append(s, 10, 20) sub := s[0:1]
make allocates a slice with length 0 and capacity 4; append adds elements; s[low:high] sub-slices.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Assuming modifying a sub-slice will not affect the original slice.Why it happens: Both slice headers point to the same underlying backing array until reallocation occurs.
How to fix: Use copy(dest, src) to clone elements into an independent slice if isolation is required.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Filter Even Numbers into a Dynamic Slice
Define a function filterEvens(nums []int) []int that takes a slice of integers.
Iterate through the slice and append only even numbers to a new result slice.
In main(), call filterEvens with [1, 2, 3, 4, 5, 6, 7, 8] and print the filtered slice.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.