Slices: Lists of Values

Keep many values together in order

9 min read

One variable holds one value. But real programs deal with collections: a list of players, a set of scores, every line in a file. Go's everyday tool for an ordered list is the slice.

Making a slice

colors := []string{"red", "green", "blue"}
fmt.Println(colors)

[]string reads as: a slice of strings. The values sit between braces, separated by commas. Printing a slice shows all its items: [red green blue].

Grabbing items by position

Each item has a numbered position called an index, and the counting starts at 0:

fmt.Println(colors[0])
fmt.Println(colors[2])
fmt.Println(len(colors))

That prints red, then blue, then 3. The first item is index 0, so the last item of a 3-item slice is index 2. Asking for colors[3] would crash the program with an index out of range error, one of the most common beginner stumbles.

Growing a slice with append

colors = append(colors, "yellow")
fmt.Println(colors)

append gives you back a new, longer slice, so you must store the result, usually right back into the same variable. Forgetting the colors = part and writing just append(colors, ...) is an error in Go, which helpfully blocks the classic mistake of appending into thin air.

Visiting every item with range

The for loop has a special form for walking through a collection:

for i, color := range colors {
    fmt.Println(i, color)
}

Each lap, range hands you the index and the value at that index. The output:

0 red
1 green
2 blue
3 yellow

If you do not need the index, ignore it with an underscore: for _, color := range colors.

Taking a slice of a slice

firstTwo := colors[0:2]
fmt.Println(firstTwo)

colors[0:2] means: start at index 0, stop before index 2. So it prints [red green]. This start-inclusive, end-exclusive style is the same convention Python uses, and it is where the name slice comes from.

Remember the two golden slice rules: counting starts at 0, and append returns a new slice that you must save.

Quick check

Q1 What is the index of the first item in a Go slice?

Q2 What is the correct way to add "gold" to a slice called colors?

Want to save your progress? It's free.

Create a free account