ProgramGuru

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.

Visual explanation for rangeRange visits each slice element in index order.Slice [10,20,30]Step 1Index 0 → 10Step 2Index 1 → 20Step 3Index 2 → 30Step 4Range visits each slice element in index order.
Range visits each slice element in index order.

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: 60

Trace 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 does _ mean in for _, value := range scores?
Choose one answer. You can try again.

Answer and explanation

Skip the index value

Correct. The slice has indexes 0, 1 and 2.

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.

    Next lesson: break Statement →