range
Start with Go range
The range form of for makes iteration over collections easier. It supplies indexes, keys or values depending on what you iterate.
What you’ll learn
- Use range with slices.
- Discard unneeded values using _.
- Know that map iteration order is unspecified.
Understand the idea
For a slice, for index, value := range values yields each index and its element value. Use _ when you do not need the index. For a map, range gives keys and values, but map traversal order is not guaranteed.
For strings, range decodes UTF-8 code points; the index is a byte offset, not necessarily a character count. Later string lessons explain that distinction in detail.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
scores := []int{10, 20, 30}
sum := 0
for index, score := range scores {
fmt.Println("Index", index, "Score", score)
sum += score
}
fmt.Println("Sum:", sum)
}
Output
Index 0 Score 10
Index 1 Score 20
Index 2 Score 30
Sum: 60Trace what the program does
The slice has indexes 0, 1 and 2. Range produces each index-value pair in order for the slice, and the loop accumulates 10, 20 and 30 into a final sum of 60.
Avoid common mistakes
- Do not rely on a fixed iteration order when ranging over a map.
- The second range value is a copy of the element value in ordinary slice iteration, not a pointer to the original element.
Try it yourself
Change the values to 5, 15 and 25. Rewrite the loop as for _, score := range scores when you no longer need the index.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go range in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.