Lesson 16 of 38 · Slices & Maps
Go Slices: append, make, len and cap
Real collections change size: loot gets picked up, adventurers join and leave the party. Arrays can't grow, but Go slices can — with the built-in append function.
In this lesson you'll learn how append really works, what len and cap mean, when to preallocate with make, and how to avoid the most famous slice surprise: two slices quietly overwriting each other's data.
append returns the updated slice
var loot []string // a nil slice is ready to use
loot = append(loot, "gold")
loot = append(loot, "gem", "sword") // several values at once
more := []string{"shield", "potion"}
loot = append(loot, more...) // ... spreads a slice into arguments
fmt.Println(loot, len(loot))
[gold gem sword shield potion] 5
append can't modify your variable: the slice descriptor (pointer, length, capacity) is passed by value. Instead it returns an updated slice, which you must store — always write s = append(s, x).
len and cap
Every slice has a length — the elements you can use — and a capacity — the room in the underlying array, counted from the slice's first element. While there is room, append writes into the existing array. When it's full, append allocates a bigger array (about twice as big for small slices), copies the elements over and returns a slice that points to the new array:
var s []int
for i := 1; i <= 5; i++ {
s = append(s, i)
fmt.Println(len(s), cap(s))
}
1 1
2 2
3 4
4 4
5 8
The exact growth rule is an implementation detail. What matters is that reallocation happens, and that after it the new slice no longer shares memory with the old one.
make and preallocation
make([]T, length, capacity) creates a slice whose array already exists. make([]int, 3) gives [0 0 0]. When you know how many elements you'll add, make an empty slice with enough capacity, so append never has to reallocate:
squares := make([]int, 0, 5) // len 0, room for 5
for i := 1; i <= 5; i++ {
squares = append(squares, i*i)
}
fmt.Println(squares, len(squares), cap(squares))
[1 4 9 16 25] 5 5
copy and the aliasing pitfall
b := a copies only the descriptor, so both names share one array. For an independent copy, use slices.Clone(a) or the built-in copy(dst, src). copy copies as many elements as the shorter of the two slices holds and returns that number. It never grows dst, so make room first:
src := []int{1, 2, 3}
dst := make([]int, len(src))
n := copy(dst, src)
dst[0] = 99
fmt.Println(src, dst, n) // [1 2 3] [99 2 3] 3
Sharing becomes a trap with append. A sub-slice may have spare capacity that reaches into its parent's elements, and appending to it then overwrites them instead of allocating:
nums := []int{1, 2, 3, 4}
first := nums[:2] // [1 2], but cap 4
first = append(first, 99) // fits, so it writes into nums[2]
fmt.Println(first, nums)
[1 2 99] [1 2 99 4]
When a result must be independent, build it in a new slice (make + append, or slices.Clone). A full slice expression, nums[:2:2], also helps: it limits the capacity to 2, so the next append must copy.
Removing an element
Go has no remove built-in. The idiom appends everything after index i onto everything before it:
nums := []int{10, 20, 30, 40}
i := 1
nums = append(nums[:i], nums[i+1:]...)
fmt.Println(nums) // [10 30 40]
slices.Delete(nums, i, i+1) does the same. Both shift elements inside the original array, so any other slice sharing that array sees them move. Work on a copy when the original must stay intact.
The slices package
The standard slices package has generic helpers for everyday jobs, and slices.Equal compares two slices, which == can't:
package main
import (
"fmt"
"slices"
)
func main() {
party := []string{"Ada", "Bo", "Cy"}
fmt.Println(slices.Contains(party, "Bo"))
fmt.Println(slices.Index(party, "Cy"), slices.Index(party, "Zed"))
slices.Reverse(party) // reverses in place
fmt.Println(party)
}
true
2 -1
[Cy Bo Ada]
Common mistakes
- Losing the result of
append:t := append(s, x)leavesswithout the new element. Writes = append(s, x). - Length instead of capacity:
make([]int, 3)already holds three zeros, so appending7gives[0 0 0 7]. Usemake([]int, 0, 3). - Thinking
b := acopies a slice: both share one array. Useslices.Clone(a). - Copying into an empty slice:
copynever growsdst, so copying into a nil slice copies nothing. - Appending to a sub-slice and overwriting the original's elements.
Assignment
The party's quartermaster needs four helpers. None of them may modify nums — the caller still needs the original list — so build every result in a new slice. The starter already imports slices, and its main tells you whether nums survived.
Evens(nums []int) []intreturns the even numbers, in their original order (-6is even too).Reversed(nums []int) []intreturns the elements in reverse order.RemoveAt(nums []int, i int) []intreturns the elements without the one at indexi. Ifiis out of range (negative, orlen(nums)or more), returnnumsunchanged.Dedupe(nums []int) []intremoves duplicates, keeping the first occurrence of each value, in order. Maps come in lesson 4 — here,slices.Containsis all you need.
Evens([]int{1, 2, 3, 4, -6, 7}) // [2 4 -6]
Reversed([]int{1, 2, 3}) // [3 2 1]
RemoveAt([]int{10, 20, 30}, 1) // [10 30]
Dedupe([]int{3, 1, 3, 2, 1}) // [3 1 2]Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Lists that grow in other languages
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .