Start learning free

LESSON 115 OF 671 · ARRAYS I

Slices vs arrays in Go

Lesson

Go has two list-like types, and mixing them up is a rite of passage. An array has a fixed size that is part of its type: [3]int holds exactly three ints, forever. A slice — []int, no number in the brackets — is what you'll actually use almost every time: a flexible window onto a hidden backing array.

A slice has two measurements:

  • len(s) — how many elements you can see right now
  • cap(s) — how many elements fit in the backing array before Go must allocate a bigger one

You grow a slice with append. When the backing array is full, append allocates a bigger array, copies everything over, and returns a NEW slice — so you must always keep the result:

nums := []int{10, 20, 30}   // len 3, cap 3 — full
nums = append(nums, 40)     // new backing array: len 4, cap 6

The trap, part 1: arrays don't grow.

Write [3]int by accident and append refuses to compile:

arr := [3]int{10, 20, 30}   // fixed-size ARRAY, not a slice
arr = append(arr, 40)
first argument to append must be a slice; have arr (variable of type [3]int)

Read it once, remember it forever — the fix is almost always that you wanted []int.


The trap, part 2: slicing SHARES memory.

s[a:b] does not copy anything. It returns a smaller window onto the SAME backing array — indices a up to (but not including) b. Mutate through the window and the original changes with it:

window := nums[1:3]   // a view of nums[1] and nums[2] — no copy
window[0] = 99        // ...this writes straight into nums[1]!

No error, no warning — just an "impossible" value appearing in a slice you never touched. This aliasing surprise bites every Go beginner exactly once. After this lesson, you'll have had yours.


Assignment
Follow the Coding Tutorial and prove all of it to yourself:

  • create nums := []int{10, 20, 30}, then print its len and cap,
  • append the value 40 and print both again — watch cap jump to 6,
  • slice out window := nums[1:3] and print it,
  • set window[0] = 99, then print nums — the original changed.

The exact expected output is:

len = 3 cap = 3
after append: len = 4 cap = 6
window = [20 30]
nums = [10 99 30 40]

Hint
append returns the (possibly brand-new) slice — always assign it back: nums = append(nums, 40).


STEP 1 OF 8
    Ctrl + Enter to check