Slices and the array behind them
A slice is a window onto an array: a pointer to the first element, a length and a capacity. Almost every list in Go is a slice, the append builtin grows one, and slicing an existing slice does not copy anything. The array from the previous lesson still exists underneath, which is what makes a slice cheap and what makes two slices able to see the same data.
make, literals and append
make([]T, len) allocates a zeroed backing array and returns a slice of that length; a third argument sets the capacity. A literal spells the elements out, and append returns a slice that may be longer. The zero value of a slice is nil, and a nil slice is already usable: it has length zero and append allocates for it.
package main
import "fmt"
func main() {
var empty []int
fmt.Println("empty:", empty, len(empty), empty == nil)
s := make([]int, 3)
fmt.Println("make:", s, len(s), cap(s))
words := []string{"go", "slices"}
words = append(words, "grow")
fmt.Println("words:", words, len(words))
nums := []int{10, 20, 30, 40}
fmt.Println("nums[1]:", nums[1])
fmt.Println("last:", nums[len(nums)-1])
}
go run basics.go
empty: [] 0 true
make: [0 0 0] 3 3
words: [go slices grow] 3
nums[1]: 20
last: 40
nums[len(nums)-1] is the last element, and there is no negative index: Go reads from the front. cap reports how many elements fit before append must allocate again, which the third section makes concrete.
A subslice is a view
all[1:4] is the elements from index 1 up to, but not including, index 4. It copies nothing: it is a new three-word descriptor that points into the same array. The length of the view is the distance between the bounds, and its capacity is the distance from the start of the view to the end of the backing array.
package main
import "fmt"
func main() {
all := []int{0, 1, 2, 3, 4, 5}
head := all[:3]
tail := all[3:]
middle := all[1:4]
fmt.Println("head:", head, "len:", len(head), "cap:", cap(head))
fmt.Println("tail:", tail, "len:", len(tail), "cap:", cap(tail))
fmt.Println("middle:", middle, "len:", len(middle), "cap:", cap(middle))
middle[0] = 100
fmt.Println("after the write, all:", all)
fmt.Println("and head:", head)
}
go run views.go
head: [0 1 2] len: 3 cap: 6
tail: [3 4 5] len: 3 cap: 3
middle: [1 2 3] len: 3 cap: 5
after the write, all: [0 100 2 3 4 5]
and head: [0 100 2]
Writing middle[0] wrote all[1], so every view of that element shows 100. This sharing is the point, and it is also the source of the classic bug: a function that returns data[:2] keeps the whole backing array alive, and the caller's append may overwrite data the callee still expects. The next lesson measures both effects.
append inside and beyond the capacity
append writes into the free space of the backing array while the capacity allows it. Two appends from the same slice therefore fight over the same cell, and the second one wins. Once the append needs more room than the capacity offers, the runtime allocates a larger array, copies the elements and returns a slice of the new one.
package main
import "fmt"
func main() {
base := make([]int, 2, 4)
base[0], base[1] = 1, 2
a := append(base, 3)
b := append(base, 4)
fmt.Println("base:", base, "len:", len(base), "cap:", cap(base))
fmt.Println("a:", a)
fmt.Println("b:", b)
grown := append(base, 5, 6, 7)
fmt.Println("grown:", grown, "len:", len(grown), "cap:", cap(grown))
grown[0] = 99
fmt.Println("base after the grown write:", base)
}
go run appendview.go
base: [1 2] len: 2 cap: 4
a: [1 2 4]
b: [1 2 4]
grown: [1 2 5 6 7] len: 5 cap: 8
base after the grown write: [1 2]
base still has length 2, so it prints two elements even though the array behind it holds 4. The grown slice does not share with base at all, which is why grown[0] = 99 left base alone. This is the rule to remember: the result of append must be assigned back, because it may be a different slice.
A slice over an array
arr[:] slices the whole array, and arr[1:3] slices part of it; both share the array's storage. append([]int(nil), s...) is the idiom for a real copy, and since Go 1.21 slices.Clone(s) says the same thing.
package main
import "fmt"
func main() {
arr := [4]int{1, 2, 3, 4}
s := arr[:]
s[0] = 100
fmt.Println("slice:", s)
fmt.Println("array:", arr)
copied := append([]int(nil), s...)
copied[0] = 7
fmt.Println("copy:", copied, "slice still:", s[0])
}
go run fromarray.go
slice: [100 2 3 4]
array: [100 2 3 4]
copy: [7 2 3 4] slice still: 100
The copy has its own array, so the write to copied[0] did not reach s. An array and a slice are still different types, though, and the compiler will not convert one to the other by itself: a slice needs a slice expression, not an assignment.
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
var s []int = arr
fmt.Println(s)
}
go build -o badtype badtype.go 2>&1 | head -3
# command-line-arguments
./badtype.go:7:16: cannot use arr (variable of type [3]int) as []int value in variable declaration
The fix is s := arr[:], which shares the array, or s := arr[0:len(arr)] when the whole array is not wanted. The maps lesson moves from an integer index to a key.
Exercises
- Build a slice of the squares 1, 4, 9, 16 with a loop and append, starting from a nil slice. How many allocations does it make for 1000 elements?
- Take s := []int{1, 2, 3, 4, 5}, cut out the element at index 2 with append(s[:2], s[3:]...) and explain what happened to the element 3.
- Write func remove(s []int, i int) []int that keeps the order, and a version that does not care about order. Which one is O(1)?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the zero value of a slice?
Answer
nil, with length zero
A declared slice is nil, and len, cap and append all accept it.
-
What does the capacity of a slice measure?
Answer
The room from its first element to the end of the backing array
len counts the elements in use, cap counts the elements that fit before append reallocates.
-
What does
appendreturn?Answer
A slice, which may share or replace the backing array
append may grow in place or copy to a larger array, so its result must be assigned back.
-
What does this program print?
package main import "fmt" func main() { s := make([]int, 2, 5) fmt.Println(len(s), cap(s)) }Answer
2 5
make sets the length to 2 and the capacity to 5.
-
What does this program print?
package main import "fmt" func main() { a := []int{0, 1, 2, 3, 4} b := a[1:3] fmt.Println(len(b), cap(b)) }Answer
2 4
The view holds two elements, and its capacity runs from index 1 to the end of the five-element array.
-
What does this program print?
package main import "fmt" func main() { a := []int{1, 2, 3} b := a[:2] b[0] = 9 fmt.Println(a) }Answer
[9 2 3]
Both slices point at the same array, so the write through b is visible through a.
-
What does this program print?
package main import "fmt" func main() { s := []int{1, 2} s = append(s, 3) fmt.Println(s, len(s)) }Answer
[1 2 3] 3
append returns the longer slice and its new length is three.
-
What does this program print?
package main import "fmt" func main() { base := make([]int, 1, 2) base[0] = 1 grown := append(base, 2, 3) grown[0] = 9 fmt.Println(base[0], grown[0], len(grown)) }Answer
1 9 3
Two appends need more than the capacity of two, so grown has its own array and base keeps 1.
-
What does
slices.Clone(s)do?Answer
Returns a slice with its own copy of the elements
Clone copies the elements into a new backing array; append([]int(nil), s...) is the older idiom.
-
Why must the result of append be assigned back?
Answer
It may be a different slice with a new array
When the capacity is full, append allocates and returns a new slice header.
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