Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

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.

Course Home

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:

  1. base had len=2 and cap=4, meaning slots 2 and 3 were free in its backing array.
  2. a := append(base, 30) saw spare room and wrote 30 directly into slot 2—without allocating a new array.
  3. base itself still had len=2, cap=4! So b := append(base, 40) also wrote into slot 2, silently overwriting a[2] with 40!
  4. Using a three-index slice base[:2:2] sets cap=2, forcing every append on safe to allocate its own independent backing array so c and d never collide.
Diagram showing a Go slice header with pointer, length, and capacity pointing to a shared backing array
Two slices sharing the same backing array when spare capacity remains.

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 calling append: That creates 10 zeroes followed by your appended values (length 11+). When appending, pass length 0 and capacity 10: make([]int, 0, 10).
  • Appending to a sub-slice without clamping capacity: Appending to items[:k] silently overwrites items[k] unless you clamp with items[:k:k] or call slices.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 until header is gone; copy those 16 bytes with slices.Clone if 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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.