Introduction
Most programs work with lists: scores, names, prices, lines of a file. Go has two list types. An array has a size that is fixed for ever, and a slice can grow and shrink. In practice you will use slices almost everywhere, and arrays only when the size is truly fixed, such as the 7 days of a week. This lesson shows how to create slices, add items to them, take parts of them and go through them with a loop.
How it works
An array's size is part of its type: [3]int is a list of exactly three ints. A slice has no size in its type: []int is a list of ints of any length. You can create one with a literal, or with make, which gives a slice of a chosen length filled with zero values:
nums := []int{5, 3, 8}
zeros := make([]int, 4)
Items are reached by index, starting at 0: nums[0] is 5. Using an index that does not exist, such as nums[3] here, stops the program with a panic. len(nums) gives the number of items. To add items, use append, and always keep the result, because the slice may have to move to bigger memory:
nums = append(nums, 1, 9)
A slice you have not set, var list []int, is a nil slice. It has length 0 and append works on it, so it is a good way to start an empty list.
A slice expression nums[1:3] gives the items from index 1 up to, but not including, index 3. You can leave out either end: nums[:2] is the first two, nums[2:] is everything from index 2. Take care: the new slice shares memory with the old one, so changing an item in the part also changes the original. Use copy or append into a new slice when you need an independent list.
To go through a slice, use range. It gives the index and the value of each item:
for i, v := range nums {
fmt.Println(i, v)
}
If you only need the values, write _ for the index. For sorting, the sort package has sort.Ints and sort.Strings, which sort a slice in place.
A slice of slices, [][]int, is a table with rows. The row grid[1] is itself a slice, so grid[1][2] is the third item of the second row. To build a table with make, first make the outer slice, then make each row.
Example
package main
import (
"fmt"
"sort"
)
func main() {
arr := [3]int{1, 2, 3}
nums := []int{5, 3, 8}
nums = append(nums, 1, 9)
fmt.Println(arr, nums, len(nums))
part := nums[1:3]
part[0] = 99
fmt.Println(part, nums)
zeros := make([]int, 3)
copy(zeros, nums)
zeros[0] = -1
fmt.Println(zeros, nums[0])
for i, v := range nums {
fmt.Print(i, "=", v, " ")
}
fmt.Println()
sort.Ints(nums)
fmt.Println(nums)
grid := make([][]int, 2)
for r := range grid {
grid[r] = make([]int, 3)
for c := range grid[r] {
grid[r][c] = r*3 + c
}
}
fmt.Println(grid, grid[1][2])
}Line by line
arris an array of 3 ints;numsis a slice made with a literal.appendadds 1 and 9 to the end, and the result goes back intonums.nums[1:3]is a part that shares memory: settingpart[0] = 99also changesnums.make([]int, 3)gives three zeros, andcopycopies items into an independent slice.rangevisits each item with its index, andsort.Intssorts the slice.gridis a slice of slices: two rows of three numbers, made withmake.
Expected result
[1 2 3] [5 3 8 1 9] 5
[99 8] [5 99 8 1 9]
[-1 99 8] 5
0=5 1=99 2=8 3=1 4=9
[1 5 8 9 99]
[[0 1 2] [3 4 5]] 5
In the real world
Slices hold almost all the data in real Go programs: the lines of a file, the rows of a database query, the items in a shopping cart. Because a slice is just a small description of a piece of memory, passing it to a function is cheap, even when it holds a million items. The append function is used constantly, and you will often start with an empty slice and add to it in a loop.
Common mistakes
- Forgetting to keep the result of append.
append(nums, 4)alone does nothing useful. - Using an index that is too big, which stops the program with a panic.
- Forgetting that a sub-slice shares memory with the original.
- Using an array where a slice is needed. Arrays of different sizes are different types.
- Writing
nums[i]in a range loop when the valuevis already given.
Best practices
- Use slices by default; use arrays only for fixed sizes.
- Start an empty list with
var list []intand add withappend. - Check
lenbefore using an index that comes from outside.
Summary
An array has a fixed size and a slice can grow. Create slices with a literal or make, add with append and keep the result, and take parts with a[low:high], remembering that they share memory. range gives each index and value, sort.Ints sorts in place, and a slice of slices makes a table.
Quick check
Key takeaways
- An array has a fixed size that is part of its type; a slice grows with append and is used much more often.
- Always keep the result: nums = append(nums, x).
- a[low:high] shares the memory of a, so changing the part changes the original.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.