Skip to content

Visit a Slice with range

The Course
•
18 min study

A three-part loop can visit a slice: start at 0 and stop before len. Because that pattern is so common, Go has a shorter form that cannot get the boundaries wrong. for index, value := range items visits each item of a slice in order, giving its index and its value. Write _, the blank identifier, in place of a variable you do not need. Ranging over an empty slice runs the body zero times.

On each pass, range sets both loop variables for you: the index counts up from 0, and the value is the item at that index. You never write the condition or the update, so there is no way to stop one item early or run one item past the end.

Predict and run

How many lines appear?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	for index, minutes := range []int{10, 25} {
		fmt.Println(index, minutes)
	}
}
Check your prediction
Text
0 10
1 25

Replace the slice with []int{} and run it again.

Choosing which variables to keep

Go reports an unused variable as an error, and loop variables are no exception. Keep only what you use:

  • for index, value := range items gives both.
  • for _, value := range items ignores the index. This is the most common form for totals and counts.
  • for index := range items gives only the index. Use it when you need to change items in place.

The blank identifier _ is not a variable at all. It is a placeholder that tells Go "a value goes here, and I am deliberately ignoring it".

Values only, then indexes only Go
package main

import (
	"fmt"
)

func main() {
	titles := []string{"Poems", "Essays"}
	for _, title := range titles {
		fmt.Println("Read:", title)
	}
	for i := range titles {
		fmt.Printf("%d. %s\n", i+1, titles[i])
	}
}
Text
Read: Poems
Read: Essays
1. Poems
2. Essays

Indexes start at 0, but people count from 1. Adding 1 when you print, as in i+1, gives a numbered list without changing the slice.

The value is a copy

The value variable holds a copy of the item, not the item itself. Changing it inside the loop does not change the slice. When you want to update the items, use the index and assign to items[i].

Update through the index Go
package main

import (
	"fmt"
)

func main() {
	sessions := []int{10, 20}
	for _, minutes := range sessions {
		minutes += 5
	}
	fmt.Println(sessions)
	for i := range sessions {
		sessions[i] += 5
	}
	fmt.Println(sessions)
}
Text
[10 20]
[15 25]
range works on more than slices

range also visits the keys of a map, which you will meet on Day 4, and the lines of input you will read on Day 5 follow the same loop-until-done idea. Since Go 1.22, for i := range 3 counts from 0 to 2, a short way to repeat something a fixed number of times.

Finding the largest value

A range loop combines naturally with an accumulator and a condition. To find the longest session, keep the largest value seen so far and replace it whenever a larger one appears. Starting from the first item avoids guessing a starting value, but it needs at least one item, so check len first when a slice might be empty.

Practice

Exercise

Your turn

The slice 25, 40 and 15 holds three sessions. Anything over 30 minutes was a timer left running, so cap every value at 30 in the slice itself, print the slice, then find and print the longest session. The output should be:

Text
[25 30 15]
Longest: 30
Your working space Go
package main

import (
	"fmt"
)

func main() {
	sessions := []int{25, 40, 15}
	fmt.Println(sessions)
}
Hint 1: the idea

The value range gives you is a copy, so a change meant to stay in the slice has to go through the index. Finding the longest is a separate pass that only reads.

Hint 2: a first step

Do the cap first and print the slice: if the first line reads [25 30 15], your change reached the slice. For the longest, start from sessions[0].

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func main() {
	sessions := []int{25, 40, 15}
	for i := range sessions {
		if sessions[i] > 30 {
			sessions[i] = 30
		}
	}
	fmt.Println(sessions)
	longest := sessions[0]
	for _, minutes := range sessions {
		if minutes > longest {
			longest = minutes
		}
	}
	fmt.Println("Longest:", longest)
}
Text
[25 30 15]
Longest: 30

Capping minutes in a for _, minutes := range sessions loop would print [25 40 15] unchanged, because each minutes is a copy. The first loop changes the slice, so it uses the index. The second only reads, so it uses the value.

Was this article helpful?

Your response is saved on this device.