The range Loop

The loops in the last two lessons used a counter: for i := 0; i < len(nums); i++. Visiting every element of a slice is so common that Go has a shorter form for it, the range loop.

package main

import "fmt"

func main() {
	fruits := []string{"apple", "pear", "fig"}
	for i, fruit := range fruits {
		fmt.Println(i, fruit)
	}
}

Output:

0 apple
1 pear
2 fig

On each pass, range gives you two values: the index and the element at that index. Here they go into the new variables i and fruit. The loop runs once for each element, from the first to the last. There is no condition to write, so you cannot get the limit wrong by one. It works the same way on arrays.

Skipping the index with _

Often you only need the values, for example to add them up. But Go does not allow a variable that you never use. If you write i and do not use it, the program does not compile:

package main

import "fmt"

func main() {
	scores := []int{70, 95, 60}
	total := 0
	for i, s := range scores {
		total += s
	}
	fmt.Println(total)
}

Output:

# command-line-arguments
./main.go:8:6: i declared and not used

Write the blank identifier _ instead of a name, as in the Multiple Return Values lesson. It tells Go "I do not need this value":

scores := []int{70, 95, 60}
total := 0
for _, s := range scores {
	total += s
}
fmt.Println("Total:", total)

Output:

Total: 225

When you only need the index, leave out the second variable: for i := range scores. This form is handy for filling a slice from input. Here the input is 4 8 15:

nums := make([]int, 3)
for i := range nums {
	fmt.Scan(&nums[i])
}
fmt.Println(nums)

Output:

[4 8 15]

The value is a copy

The value variable holds a copy of the element. If you change it, the slice does not change:

prices := []int{5, 10, 20}
for _, p := range prices {
	p = p * 2
}
fmt.Println(prices)

Output:

[5 10 20]

Go compiles this without any error, but the loop only doubled the copies in p. To change the elements, use the index and write into the slice:

prices := []int{5, 10, 20}
for i := range prices {
	prices[i] = prices[i] * 2
}
fmt.Println(prices)

Output:

[10 20 40]

Two slices that belong together

In The for Loop lesson, for i := range 5 counted from 0 to 4. A range loop over a slice with only the index does the same kind of counting: it gives 0, 1, 2 and so on, up to the last index of the slice. That is what you need when two slices hold matching data at the same index:

names := []string{"Alice", "Bob", "Emma"}
scores := []int{90, 75, 82}
for i := range names {
	fmt.Println(names[i], scores[i])
}

Output:

Alice 90
Bob 75
Emma 82

range also works on maps and strings, and it gives different values there. The Maps and Strings section shows those forms.

In the exercise, use a range loop with an index and a value to print each delivery time with its number and add up the total.