range over an integer
A runner who counts laps alone can lose track: start the count from the wrong number or run an extra lap. Many stadiums have a scoreboard that counts the laps, so all the runner has to do is run.
A three-part loop is the runner who counts alone. To repeat an action n times, it keeps a counter, a condition and a post statement. Those are three places to make a mistake:
- starting at one instead of zero;
- writing
<=instead of<; - forgetting the post statement.
For this kind of repetition, Go has a short form with the range keyword, and that is the scoreboard:
package main
import "fmt"
func main() {
for i := range 5 {
fmt.Print(i, " ") // 0 1 2 3 4
}
}Let's see what the program printed. The body ran five times, and i was 0, 1, 2, 3 and 4 in turn.
Two forms of range over a number
This form comes in two shapes: with a variable for the iteration number and without one.
With a variable: for i := range n
The header reads left to right:
foris the loop keyword;i :=declares a variable for the iteration number;range nsays how many iterations to run.
The loop runs n iterations, and the variable i takes the values from 0 to n - 1 in turn. It does the same as for i := 0; i < n; i++, but Go keeps the counter and the post statement for you. The variable i never takes the value 5: the last iteration runs with i equal to 4.
Here this scoreboard differs from a real one: it starts counting at zero. A person calls the first lap the first, but range calls it lap zero. Keep that in mind whenever the iteration number goes into a calculation.
Instead of a number, you can write a variable or an expression of type int:
for i := range countruns the bodycounttimes;- if the value is zero or negative, the body never runs;
- when counting does not start at zero or goes backward, you need a three-part loop, such as
for i := 5; i >= 1; i--.
Without a variable: for range n
When the iteration number is not needed, no variable is declared at all. The form for range 3 runs the body three times:
for range 3 {
fmt.Print("Go ") // Go Go Go
}You cannot declare i and leave it unused: an unused variable is a compile error, and the same rule holds in a loop. So a repetition with no number is written as for range n, with no name.
The break and continue statements work in both forms the same way as in a three-part loop.
What changed in Go 1.22
This form appeared in Go 1.22, so older tutorials do not have it. The same version changed two rules:
rangeover an integer appeared;- each iteration of any
forloop gets its own copy of the loop variable.
The programs in this theme show no difference from the second rule, but interviewers often ask about this change.
Common mistake
A loop over range 5 is meant to add up the numbers from 1 to 5:
s := 0
for i := range 5 { // ✗
s += i
}
fmt.Println(s)The program prints 10, not 15: the variable i runs from 0 to 4, and five never gets into the sum. Add i + 1 instead, or write a three-part loop: for i := 1; i <= 5; i++.
Key points
for i := range nrunsniterations, anditakes the values from0ton - 1.- When
nis zero or negative, the body never runs. for range nrepeats the bodyntimes with no variable.- Counting from something other than zero, or backward, needs a three-part loop.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.