append, capacity and shared backing arrays
The previous lesson showed that two slices can see the same array. This one looks at the three numbers that make that true, at the growth strategy behind append, at the full slice expression that closes a view, and at copy, which is the one operation that moves elements.
Three words
A slice is a descriptor of three words: a pointer to the first element of the window, a length, and a capacity. Passing a slice to a function copies the descriptor, not the array, which is why a function that reslices its argument cannot change the caller's length but can change the elements. A slice is therefore cheap to pass and is the reason Go code passes []byte where C passes a pointer and a length.
How append grows
When the capacity is exhausted, append allocates a new array, copies the elements and returns a slice of the new one. The runtime starts a slice at a small capacity, doubles it while the slice is small and switches to smaller jumps once it is large, so a loop that appends element by element stays close to linear in total work even though a single append may copy. The program prints every capacity change while it appends 1025 integers.
package main
import "fmt"
func main() {
var s []int
last := cap(s)
for i := 0; i < 1025; i++ {
s = append(s, i)
if cap(s) != last {
fmt.Printf("len %4d cap %4d\n", len(s), cap(s))
last = cap(s)
}
}
}
go run growth.go
len 1 cap 4
len 5 cap 8
len 9 cap 16
len 17 cap 32
len 33 cap 64
len 65 cap 128
len 129 cap 256
len 257 cap 512
len 513 cap 848
len 849 cap 1280
The jumps are the allocations, and the pattern is the runtime's, not the language's: the specification promises only that append returns a slice with the new elements, and code must not depend on a particular capacity. What code may rely on is that appending n elements costs O(n) copies in total, which is why a program that knows the final size calls make([]T, 0, n) first.
The full slice expression
s[low:high:max] sets the capacity as well: the new slice has max - low elements of room. It is the tool for handing out a view that the receiver cannot append into, which is a real bug when the view is shorter than the array behind it.
package main
import "fmt"
func main() {
all := []int{0, 1, 2, 3, 4, 5}
safe := all[1:3:3]
fmt.Println("safe:", safe, "len:", len(safe), "cap:", cap(safe))
appended := append(safe, 99)
fmt.Println("appended:", appended)
fmt.Println("all after the safe append:", all)
dangerous := all[1:3]
fmt.Println("dangerous cap:", cap(dangerous))
dangerous = append(dangerous, 77)
fmt.Println("dangerous:", dangerous)
fmt.Println("all after the dangerous append:", all)
}
go run fullslice.go
safe: [1 2] len: 2 cap: 2
appended: [1 2 99]
all after the safe append: [0 1 2 3 4 5]
dangerous cap: 5
dangerous: [1 2 77]
all after the dangerous append: [0 1 2 77 4 5]
safe has capacity 2, so its append had to allocate and all kept its six elements. dangerous had capacity 5, so its append wrote into all[3] and the original slice changed without a line that mentions it. A function that returns a subslice to a caller it does not trust returns s[1:3:3] or a clone.
copy and clone
copy(dst, src) moves min(len(dst), len(src)) elements and returns how many it moved. It handles overlapping slices correctly, as if it copied through a temporary buffer, and it never allocates: the destination must already have room.
package main
import "fmt"
func main() {
src := []int{1, 2, 3, 4, 5}
dst := make([]int, 3)
n := copy(dst, src)
fmt.Println("copied:", n, dst)
overlap := []int{1, 2, 3, 4, 5}
copy(overlap[1:], overlap)
fmt.Println("shifted right:", overlap)
short := []int{9, 9, 9, 9, 9, 9}
copy(short[2:], src)
fmt.Println("partly replaced:", short)
same := append([]int(nil), src...)
fmt.Println("clone equal:", same)
}
go run copying.go
copied: 3 [1 2 3]
shifted right: [1 1 2 3 4]
partly replaced: [9 9 1 2 3 4]
clone equal: [1 2 3 4 5]
copy(overlap[1:], overlap) shifted the slice right by one without losing data, and copy(short[2:], src) stopped at the end of the destination. For a fresh independent copy, slices.Clone (Go 1.21) or append([]T(nil), s...) allocates the exact length.
The aliasing bug in one function
A function that returns s[:2] hands back a window whose capacity still reaches the end of the caller's array. The caller appends, and the write lands in data the function's author thought was private.
package main
import "fmt"
func firstTwo(s []int) []int {
return s[:2]
}
func main() {
data := []int{10, 20, 30, 40}
head := firstTwo(data)
head = append(head, 99)
fmt.Println("head:", head)
fmt.Println("data:", data)
}
go run alias.go
head: [10 20 99]
data: [10 20 99 40]
Neither line is wrong on its own, which is what makes the bug expensive: the append was legal because the capacity allowed it. The fix is return s[:2:2], and go vet cannot see this one. The next lesson changes the container to one that has no capacity at all.
A capacity smaller than the length
make takes the length first and the capacity second, so the two cannot be swapped by accident: the compiler rejects a capacity below the length.
package main
import "fmt"
func main() {
s := make([]int, 5, 3)
fmt.Println(s)
}
go build -o badcap badcap.go 2>&1 | head -3
# command-line-arguments
./badcap.go:6:19: invalid argument: length and capacity swapped
The message names the builtin and both numbers. The same rule holds for make([]byte, 0, 1024), the growable buffer with room for a kilobyte from the start.
Exercises
- Preallocate make([]int, 0, 1000) and append 1000 numbers. How many allocations does the growth program make for the same work?
- Use s[2:4:4] to pass a view to a function that appends to it, and check that the caller's slice is unchanged.
- Delete the element at index 2 with copy(s[2:], s[3:]) and s = s[:len(s)-1]. Where does the old last element still live?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a slice hold?
Answer
A pointer, a length and a capacity
The three-word descriptor is what makes a slice cheap to pass and what makes views share data.
-
What does
s[1:3:4]set the capacity of the new slice to?Answer
3
The third index is an upper bound on the capacity, so max - low is 4 - 1 = 3.
-
What does this program print?
package main import "fmt" func main() { s := []int{} for i := 0; i < 5; i++ { s = append(s, i) } fmt.Println(len(s), cap(s)) }Answer
5 8
Appending five elements fills the capacity of 8 that the runtime chose.
-
What does this program print?
package main import "fmt" func main() { all := []int{0, 1, 2, 3, 4, 5} view := all[1:3:3] view = append(view, 99) fmt.Println(view, all) }Answer
[1 2 99] [0 1 2 3 4 5]
The capacity of 3 forces an allocation, so all keeps its original elements.
-
What does this program print?
package main import "fmt" func main() { src := []int{1, 2, 3, 4, 5} dst := make([]int, 3) n := copy(dst, src) fmt.Println(n, dst) }Answer
3 [1 2 3]
copy stops at the shorter length and returns the number of elements it moved.
-
What does this program print?
package main import "fmt" func main() { s := []int{1, 2, 3, 4, 5} copy(s[1:], s) fmt.Println(s) }Answer
[1 1 2 3 4]
copy treats an overlap as if it used a temporary buffer, so the slice moves right by one.
-
What does this program print?
package main import "fmt" func firstTwo(s []int) []int { return s[:2] } func main() { data := []int{10, 20, 30, 40} head := firstTwo(data) head = append(head, 99) fmt.Println(data) }Answer
[10 20 99 40]
head has capacity 4, so its append writes into data[2].
-
What does
copy(dst, src)return?Answer
The number of elements copied
The count is min(len(dst), len(src)), and it never allocates.
-
Which of these makes an independent copy of a slice?
Answer
slices.Clone(s)
Clone allocates a new backing array; the slice expressions are views.
-
What does
make([]int, 5, 3)do?Answer
It does not compile: the length is larger than the capacity
The compiler rejects a capacity below the length in make.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev