Arrays, Slices, and Why append Matters
Distinguish fixed arrays from dynamic slices, inspect len and cap, and avoid backing-array aliasing bugs when using append. After this, you can work with Go slices without accidental mutations.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Why Go Exists and When to Pick It
-
Run Your First Go Program
-
-
-
Values, Control Flow, and Functions
-
Variables, Types, and Zero Values
-
If, For Loops, and Multiple Return Values
-
-
-
Slices, Maps, and Structs
-
Arrays, Slices, and Why append Matters
-
Maps, Structs, and Pointer Receivers
-
-
-
Errors, Packages, and Testing
-
Handle Errors Without Hiding Them
-
Packages, Exports, and go test
-
-
-
Files, JSON, and a Small HTTP Server
-
Read Files and Decode JSON Structs
-
Build and Test a Small net/http Server
-
-
-
Pointers, Modules, and CLIs
-
Pointers and Memory Basics
-
Managing Dependencies and internal/ Packages
-
Building CLIs With flag, os.Getenv, and Exit Codes
-
-
Coming from Python lists or JavaScript arrays, Go slices look deceptively familiar—until one day calling append on variable b silently overwrites an element inside variable a. That bug makes total sense once you know what a slice actually is in memory: a tiny 3-field header pointing into a shared backing array.
Skip ahead
If you already understand array copying vs. slice headers, why append can alias a shared backing array, and how base[:2:2] or slices.Clone prevents it, move on to "Maps, Structs, and Pointer Receivers."
Experiment 1: Arrays copy everything; slices share their backing array
In Go, an array ([3]int) has a fixed length baked into its type. Assigning an array copies every element. A slice ([]int) has no fixed length in its type; assigning a slice copies only its 24-byte header (pointer, length, capacity), so both variables point to the exact same elements in memory:
package main
import (
"fmt"
"slices"
)
func main() {
arr1 := [3]int{10, 20, 30}
arr2 := arr1
arr2[0] = 99
fmt.Println("arrays:", arr1, arr2)
s1 := []int{10, 20, 30}
s2 := s1
s2[0] = 99
fmt.Println("slices shared:", s1, s2)
s3 := slices.Clone(s1)
s3[0] = 1
fmt.Println("after Clone:", s1, s3)
}
arrays: [10 20 30] [99 20 30]
slices shared: [99 20 30] [99 20 30]
after Clone: [99 20 30] [1 20 30]
When you actually want an independent copy of a slice so edits to one cannot leak into the other, call slices.Clone(s1).
Experiment 2: Zero-value nil slices and how capacity grows
Unlike maps, a nil slice is completely usable right away: len, cap, range, and append all work cleanly. Watch how Go grows capacity automatically when an array fills up:
var s []int
fmt.Printf("nil slice: s==nil:%v len=%d cap=%d\n", s == nil, len(s), cap(s))
for i := 1; i <= 5; i++ {
s = append(s, i)
fmt.Printf("append %d -> len=%d cap=%d\n", i, len(s), cap(s))
}
nil slice: s==nil:true len=0 cap=0
append 1 -> len=1 cap=4
append 2 -> len=2 cap=4
append 3 -> len=3 cap=4
append 4 -> len=4 cap=4
append 5 -> len=5 cap=8
On the first append, Go allocates a backing array with capacity 4 so the next three appends cost zero allocations. On item 5, capacity is full, so Go allocates a new array of capacity 8, copies the old 4 items over, and returns a new slice header pointing to the larger array. That is why you must assign the return value back (s = append(s, i)).
Experiment 3: Why two append calls can overwrite each other
Now watch the subtle trap that happens when you start with a slice that has spare capacity (common after sub-slicing all[:2] or calling make([]int, 2, 4)):
base := make([]int, 2, 4)
base[0], base[1] = 10, 20
a := append(base, 30)
b := append(base, 40) // overwrites 30 in shared backing array!
fmt.Println("aliased a:", a, "b:", b)
safe := base[:2:2] // cap=2 forces new allocation on append
c := append(safe, 30)
d := append(safe, 40)
fmt.Println("isolated c:", c, "d:", d)
aliased a: [10 20 40] b: [10 20 40]
isolated c: [10 20 30] d: [10 20 40]
Trace what happened step by step:
basehadlen=2andcap=4, meaning slots2and3were free in its backing array.a := append(base, 30)saw spare room and wrote30directly into slot2—without allocating a new array.baseitself still hadlen=2, cap=4! Sob := append(base, 40)also wrote into slot2, silently overwritinga[2]with40!- Using a three-index slice
base[:2:2]setscap=2, forcing everyappendonsafeto allocate its own independent backing array socanddnever collide.
Experiment 4: Pre-allocating when you know the final length
If you are transforming 10,000 database rows into a slice, writing var out []Row forces Go to allocate and copy the backing array ~14 times as it doubles. Writing out := make([]Row, 0, len(rows)) allocates the right array once up front while keeping len(out) == 0 so append starts at index 0.
Common mistakes
- Writing
make([]int, 10)and then callingappend: That creates 10 zeroes followed by your appended values (length 11+). When appending, pass length0and capacity10:make([]int, 0, 10). - Appending to a sub-slice without clamping capacity: Appending to
items[:k]silently overwritesitems[k]unless you clamp withitems[:k:k]or callslices.Clone. - Pinning a huge backing array with a tiny sub-slice: Taking
header := bigFileBytes[:16]keeps the entire 50 MB backing array alive in memory untilheaderis gone; copy those 16 bytes withslices.Cloneif you discard the big buffer.
💡 Tip
Prefer var items []string over items := []string{} for empty slices—except when encoding to JSON for an API that expects [] instead of null.
What happens if you skip this step
Without understanding slice capacity and backing arrays, you eventually hit a "ghost mutation" bug where building two derived routes or lists from a shared prefix causes the second list to corrupt the first—passing every single-path test and failing only when both paths run together.
If nums := []int{1, 2, 3, 4} and you take head := nums[:2], what happens to nums[2] when you run head = append(head, 99)?
About
Distinguish fixed arrays from dynamic slices, inspect len and cap, and avoid backing-array aliasing bugs when using append. After this, you can work with Go slices without accidental mutations.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.