Skip to content

Reason About append

The Course
•
25 min study

len counts the elements in the slice: the ones you can index. cap counts how many fit in the underlying array, starting from the slice's first element, before append needs new storage. That second number decides something important: whether append writes into an array that another slice is already using, or copies everything to a fresh one.

  • When len < cap, append writes the new element into the spare room of the same array and returns a longer header. Any other slice over that array can see the write.
  • When len == cap, append allocates a bigger array, copies the elements across and writes there. The original array is untouched.

A three-index slice such as base[:1:1] sets the capacity as well as the length, so you can force the second case.

Predict and run

What does the second original element become?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	base := []int{10, 20, 30}
	prefix := base[:1]
	fmt.Println(len(prefix), cap(prefix))
	prefix = append(prefix, 99)
	fmt.Println(base, prefix)
}
Check your prediction
Text
1 3
[10 99 30] [10 99]

Use base[:1:1] to limit the prefix capacity. Predict what base contains.

Trace it

prefix := base[:1] has length 1, but its capacity is 3, because the array has two more boxes after its first element. append(prefix, 99) sees spare room and writes 99 into the next box, which is base[1]. No error and no warning: base just changed.

Two appends, one array

The same rule produces one of Go's most confusing bugs. Two slices built by appending to the same base can end up sharing the box they each think is theirs. The example builds its base with make([]string, 1, 4): make with three arguments gives a slice of length 1 whose array has room for 4, so there is spare capacity from the start.

The second append overwrites the first Go
package main

import (
	"fmt"
)

func main() {
	base := make([]string, 1, 4)
	base[0] = "Read"
	monday := append(base, "Draft")
	tuesday := append(base, "Review")
	fmt.Println(monday, tuesday)
}
Text
[Read Review] [Read Review]

base has length 1 and capacity 4. Both appends write into index 1 of the same array, so tuesday's write replaced monday's. Change make([]string, 1, 4) to make([]string, 1, 1) and run it again: with no spare room, each append gets its own new array, and you get [Read Draft] [Read Review]. The code didn't change, only the capacity did, which is why this bug can appear and disappear as data grows.

Practice

Exercise

Your turn

Write withExtra(base []int, extra int) []int, which returns base followed by extra. It must never change the caller's data, even when base has spare capacity. The starter calls it twice on a slice with room to spare and prints everything. Once your function is safe, the output should be:

Text
[10 20] [10 20 30] [10 20 40]
Your working space Go
package main

import (
	"fmt"
)

func withExtra(base []int, extra int) []int {
	return append(base, extra)
}

func main() {
	base := make([]int, 2, 10)
	base[0], base[1] = 10, 20
	a := withExtra(base, 30)
	b := withExtra(base, 40)
	fmt.Println(base, a, b)
}
Hint 1: the idea

Run the starter first: a and b share a box, as in the example above. The fix is to make sure append has no spare room to write into, so it has to allocate.

Hint 2: a first step

Print cap(base) inside withExtra: it is 10. A three-index slice of base whose capacity equals its length leaves append no choice.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func withExtra(base []int, extra int) []int {
	return append(base[:len(base):len(base)], extra)
}

func main() {
	base := make([]int, 2, 10)
	base[0], base[1] = 10, 20
	a := withExtra(base, 30)
	b := withExtra(base, 40)
	fmt.Println(base, a, b)
}
Text
[10 20] [10 20 30] [10 20 40]

base[:len(base):len(base)] keeps every element but sets the capacity to the length, so append must copy to a new array. The starter printed [10 20] [10 20 40] [10 20 40]: b's write landed in the box a was using. The next lesson makes an independent copy explicitly with copy.

Was this article helpful?

Your response is saved on this device.