Skip to content

Keep Values in a Slice

The Course
•
18 min study

A reading log needs more than one session, and declaring first, second and third variables does not scale. A slice holds a sequence of values of one type. []int{15, 20} is a slice of two integers. Indexing starts at zero, and len gives the number of items. append returns the longer slice, which may use new storage, so always assign its result back.

The type is written []int, read as "slice of int". Every item in the slice has that type, so a []int cannot hold text and a []string cannot hold numbers. The values in braces after the type are the starting items, separated by commas.

Predict and run

Which value is at index 1?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	sessions := []int{15, 20}
	sessions = append(sessions, 25)
	fmt.Println(sessions[1], len(sessions))
}
Check your prediction
Text
20 3

Try sessions[3]. Run it, read the index out of range message and restore the valid index.

Indexes run from 0 to len minus 1

A slice of three items has indexes 0, 1 and 2. The first item is always sessions[0], and the last is sessions[len(sessions)-1]. Asking for an index outside that range does not return a placeholder value; the program stops with a panic, a run-time error that reports index out of range [3] with length 3. Go checks every index, so a mistake fails loudly instead of reading unrelated memory.

You can also assign to an index to replace an item. The slice keeps its length; only the value at that position changes.

Read and replace by index Go
package main

import (
	"fmt"
)

func main() {
	titles := []string{"Poems", "Essays", "Letters"}
	fmt.Println(titles[0])
	fmt.Println(titles[len(titles)-1])
	titles[1] = "Short stories"
	fmt.Println(titles, len(titles))
}
Text
Poems
Letters
[Poems Short stories Letters] 3

Println prints a whole slice in square brackets with spaces between the items. That is handy for checking a slice, though a report usually formats each item itself.

Starting empty and growing

Often you do not know the values in advance. Start with an empty slice, []int{}, and append to it as values arrive. append can add several values in one call. A slice declared with var sessions []int is also empty: its zero value is a slice with length 0, and append works on it the same way.

Grow a slice Go
package main

import (
	"fmt"
)

func main() {
	var sessions []int
	fmt.Println(len(sessions))
	sessions = append(sessions, 15)
	sessions = append(sessions, 20, 25)
	fmt.Println(sessions, len(sessions))
}
Text
0
[15 20 25] 3
Always store what append returns

append(sessions, 15) on its own line is a compile error, because its result is not used. Writing more := append(sessions, 15) compiles but leaves sessions unchanged. The pattern to remember is sessions = append(sessions, value): the same name on both sides.

A slice of a slice

sessions[1:3] makes a new slice of the items from index 1 up to, but not including, index 3. Leave out a number to start at the beginning or run to the end: sessions[:2] is the first two items. This shares storage with the original rather than copying it, which matters later. For now, use it to read part of a slice.

Practice

Exercise

Your turn

Start with an empty slice of int. Append three sessions: 25, 10 and 40 minutes. The 10 was a typo for 15, so replace it by index. Then print the number of sessions, the last session using len, and the first two sessions as a slice of the slice. The output should be:

Text
3
40
[25 15]
Your working space Go
package main

func main() {
	// Write your code here.
}
Hint 1: the idea

Indexes start at 0, so the typo is at index 1 and the last item is at len minus 1. append returns the grown slice, and you have to store it.

Hint 2: a first step

Write var sessions []int, append the three values, and print sessions. You should see [25 10 40] before you change anything.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func main() {
	var sessions []int
	sessions = append(sessions, 25)
	sessions = append(sessions, 10)
	sessions = append(sessions, 40)
	sessions[1] = 15
	fmt.Println(len(sessions))
	fmt.Println(sessions[len(sessions)-1])
	fmt.Println(sessions[:2])
}
Text
3
40
[25 15]

sessions[3] would stop the program with index out of range [3] with length 3. len(sessions)-1 always names the last item, however many you append. sessions[:2] stops before index 2, so it holds two items.

Was this article helpful?

Your response is saved on this device.