Lesson 6 of 20 · Part 2: Working with data
Arrays and slices
Learn Go arrays and slices for beginners. Create slices, use append, len and cap, slice expressions, copy, the slices package, and avoid the shared-array trap.
5 min read · Updated · Beginner friendly
What you'll learn
- Know the difference between an array and a slice
- Create slices and grow them with append
- Understand len, cap and how slices share memory
- Sort, search and copy with the slices package
Real programs rarely work with just one value. You have a list of scores, a set of file names, the lines of a document. Go gives you two ways to keep an ordered list of values of the same type: arrays and slices. You will use slices almost all the time, but they are built on top of arrays, so we start there.
Arrays: a fixed number of values
An array holds a fixed number of elements. The length is part of its type:
package main
import "fmt"
func main() {
var scores [3]int // three ints, all starting at 0
scores[0] = 90
scores[2] = 75
fmt.Println(scores)
fmt.Println("first:", scores[0], "length:", len(scores))
days := [7]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
fmt.Println(days[5], days[6])
}[90 0 75]
first: 90 length: 3
Sat Sun- Indexes start at 0, so the last element of a 3-element array is at index
2. - Unset elements hold the zero value (
0here). - Accessing an index outside the array is an error. If the compiler can see it, the program won’t build; otherwise the program stops with
index out of range.
Because the length is part of the type, [3]int and [4]int are different types, and an array can never grow. That’s too limiting for most tasks, which is why Go has slices.
Slices: flexible lists
A slice looks almost the same, but you leave the length out of the brackets:
package main
import "fmt"
func main() {
fruits := []string{"apple", "banana"}
fmt.Println(fruits, len(fruits))
fruits = append(fruits, "cherry")
fruits = append(fruits, "date", "elderberry")
fmt.Println(fruits, len(fruits))
fruits[0] = "apricot"
fmt.Println(fruits[0], fruits[len(fruits)-1])
}[apple banana] 2
[apple banana cherry date elderberry] 5
apricot elderberryappend adds one or more elements to the end and returns the new slice. Always assign the result back: fruits = append(fruits, ...). Forgetting this is a common mistake, and go vet will remind you.
Looping over a slice
Use for ... range, which you met in lesson 5:
package main
import "fmt"
func main() {
temps := []float64{21.5, 23.0, 19.5, 25.0}
sum := 0.0
for _, t := range temps {
sum += t
}
fmt.Printf("average: %.2f\n", sum/float64(len(temps)))
for i := range temps {
temps[i] += 1 // change the slice through its index
}
fmt.Println(temps)
}average: 22.25
[22.5 24 20.5 26]Empty and nil slices
A slice declared without a value is nil: it has length 0 and no elements yet. A nil slice works perfectly with len, range and append, so you rarely need to treat it specially.
package main
import "fmt"
func main() {
var names []string
fmt.Println(names == nil, len(names))
names = append(names, "Ada")
fmt.Println(names, len(names))
}true 0
[Ada] 1Slicing: taking part of a slice
The slice expression s[low:high] gives you the elements from index low up to, but not including, high:
package main
import "fmt"
func main() {
letters := []string{"a", "b", "c", "d", "e", "f"}
fmt.Println(letters[1:4]) // index 1, 2, 3
fmt.Println(letters[:3]) // from the start
fmt.Println(letters[3:]) // to the end
fmt.Println(letters[:]) // everything
}[b c d]
[a b c]
[d e f]
[a b c d e f]A handy way to remember it: letters[1:4] has 4 - 1 = 3 elements.
How slices work: len, cap and the shared array
This part is where many beginners get surprised, so take it slowly.
A slice doesn’t store its elements itself. It is a small view onto an array that lives somewhere in memory. The view has three parts:
- a pointer to the first element it can see,
- a length (
len): how many elements are in the slice, - a capacity (
cap): how many elements fit before the underlying array runs out.
When you slice a slice, the new slice shares the same array. Changing an element through one is visible through the other:
package main
import "fmt"
func main() {
original := []int{1, 2, 3, 4, 5}
part := original[1:3]
fmt.Println("part:", part, "len:", len(part), "cap:", cap(part))
part[0] = 99 // also changes original!
fmt.Println("original:", original)
}part: [2 3] len: 2 cap: 4
original: [1 99 3 4 5]part starts at index 1 of the array, so it can see 4 elements of capacity (indexes 1 to 4), even though its length is only 2.
What append does
When there is spare capacity, append writes into the existing array. When the array is full, append allocates a new, bigger array, copies the elements across, and returns a slice pointing at the new array:
package main
import "fmt"
func main() {
var nums []int
for i := range 6 {
nums = append(nums, i)
fmt.Printf("len=%d cap=%d %v\n", len(nums), cap(nums), nums)
}
}len=1 cap=1 [0]
len=2 cap=2 [0 1]
len=3 cap=4 [0 1 2]
len=4 cap=4 [0 1 2 3]
len=5 cap=8 [0 1 2 3 4]
len=6 cap=8 [0 1 2 3 4 5]Notice how the capacity roughly doubles each time it runs out. That keeps append fast on average. (The exact growth rule is an implementation detail and may differ between Go versions, so never rely on specific capacity values.)
The shared-array trap
If two slices share an array, append on one of them can overwrite elements the other one can see, but only while there is spare capacity. When you need an independent copy, make one explicitly with slices.Clone or copy (below).
Making a slice with make
If you know roughly how many elements you will need, create the slice with make and give it a capacity up front. This avoids repeated re-allocations:
package main
import "fmt"
func main() {
squares := make([]int, 0, 10) // length 0, capacity 10
for i := 1; i <= 5; i++ {
squares = append(squares, i*i)
}
fmt.Println(squares, len(squares), cap(squares))
grid := make([]string, 3) // length 3: three empty strings, ready to set by index
grid[1] = "middle"
fmt.Printf("%q\n", grid)
}[1 4 9 16 25] 5 10
["" "middle" ""]Copying slices
copy(dst, src) copies elements from one slice to another and returns how many it copied. slices.Clone makes a full independent copy in one call:
package main
import (
"fmt"
"slices"
)
func main() {
src := []int{1, 2, 3}
dst := make([]int, len(src))
n := copy(dst, src)
dst[0] = 100
fmt.Println("copied", n, "src:", src, "dst:", dst)
clone := slices.Clone(src)
clone[1] = 200
fmt.Println("src:", src, "clone:", clone)
}copied 3 src: [1 2 3] dst: [100 2 3]
src: [1 2 3] clone: [1 200 3]Changing dst or clone doesn’t affect src, because they have their own arrays.
The slices package
The standard library’s slices package has ready-made helpers for common jobs:
package main
import (
"fmt"
"slices"
)
func main() {
nums := []int{42, 7, 19, 3, 25}
slices.Sort(nums)
fmt.Println("sorted:", nums)
fmt.Println("contains 19?", slices.Contains(nums, 19))
fmt.Println("index of 25:", slices.Index(nums, 25))
fmt.Println("min:", slices.Min(nums), "max:", slices.Max(nums))
slices.Reverse(nums)
fmt.Println("reversed:", nums)
nums = slices.Insert(nums, 1, 100) // insert 100 at index 1
nums = slices.Delete(nums, 3, 4) // remove the element at index 3
fmt.Println("edited:", nums)
}sorted: [3 7 19 25 42]
contains 19? true
index of 25: 3
min: 3 max: 42
reversed: [42 25 19 7 3]
edited: [42 100 25 7 3]The sort package also has sort.Strings and sort.Ints, which you’ll see in older code. New code usually uses slices.
Slices of slices
A slice can hold other slices, which is a simple way to build a grid or table:
package main
import "fmt"
func main() {
board := [][]string{
{"X", "O", "X"},
{" ", "X", "O"},
{"O", " ", "X"},
}
for _, row := range board {
fmt.Println(row)
}
fmt.Println("centre:", board[1][1])
}[X O X]
[ X O]
[O X]
centre: XCommon mistakes
Not assigning the result of append. append(list, x) on its own does nothing useful; write list = append(list, x).
Index out of range. s[len(s)] is always out of range: the last element is s[len(s)-1]. Check the length before you index into a slice that might be empty.
Expecting a slice expression to copy. b := a[0:2] shares memory with a. Use slices.Clone when you need an independent copy.
Changing the loop variable in range. for _, v := range s { v *= 2 } changes a copy. Use for i := range s { s[i] *= 2 }.
Exercises
1. Highest score. Given scores := []int{67, 92, 85, 49, 78}, find the highest score with a loop (not slices.Max) and print it with its index.
Show solution
package main
import "fmt"
func main() {
scores := []int{67, 92, 85, 49, 78}
best, bestIndex := scores[0], 0
for i, s := range scores {
if s > best {
best, bestIndex = s, i
}
}
fmt.Printf("highest score %d at index %d\n", best, bestIndex)
}highest score 92 at index 12. Keep the even numbers. Build a new slice containing only the even numbers from 1 to 20.
Show solution
package main
import "fmt"
func main() {
var evens []int
for n := 1; n <= 20; n++ {
if n%2 == 0 {
evens = append(evens, n)
}
}
fmt.Println(evens)
}[2 4 6 8 10 12 14 16 18 20]3. Reverse in place. Reverse []string{"one", "two", "three", "four"} without using slices.Reverse. Hint: swap the first and last elements, then move inwards.
Show solution
package main
import "fmt"
func main() {
words := []string{"one", "two", "three", "four"}
for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
fmt.Println(words)
}[four three two one]4. Predict the output. What does this print? Run it to check your answer.
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4}
b := a[:2]
b = append(b, 100)
fmt.Println(a, b)
}Show solution
[1 2 100 4] [1 2 100]b has length 2 but capacity 4, so append writes 100 into the shared array at index 2, overwriting a[2]. This is the shared-array trap in action.
Recap
- Arrays have a fixed length that is part of their type; slices can grow.
appendadds elements and returns a new slice: always assign it back.- A slice is a view onto an array with a length and a capacity; slicing shares memory.
- Use
maketo pre-size a slice andcopyorslices.Cloneto get an independent copy. - The
slicespackage sorts, searches, inserts and deletes for you.
Next up: maps, for looking values up by a key.
Finished this lesson?
Your progress is saved in this browser only.