Lesson contents

Go — Range loops, break, and continue

In Go, for range can produce both the index and the current value of a slice. Use the blank identifier for an unused index, continue to skip a value, and break to stop.

A simple example

Print the numbers 1 to 3

  1. Start with Start at 1
  2. Do this Visit 1, 2, 3
  3. Result 1 → 2 → 3
Each pass prints one number on its own line. After 3 the loop has no more values to visit.
main.go
package main

import "fmt"


func main() {
    for _, n := range []int{1, 2, 3} {
        fmt.Println(n)
    }
}
Output
1
2
3
Advertisements

Stop at the end of a batch

The blank identifier discards the index yielded by range. The second value is the reading. break ends the loop and continue advances to the next element.

Readings: 4, −1, 0, 7. End marker: 0. This batch totals: 4.
Find the end of a scanner batch

A scanner sends 4, then an invalid reading of −1, then the batch marker 0. Add 4, skip the invalid reading and stop at the marker. The later 7 belongs to the next batch.

Run the example

Go 1.20 or later. Run these commands from the directory containing the example.

go run main.go
main.go
package main

import (
	"fmt"
)

func main() {
	total := 0
	for _, reading := range []int{4, -1, 0, 7} {
		if reading == 0 {
			break
		}
		if reading < 0 {
			continue
		}
		total += reading
	}
	fmt.Println(total)
}
Output
4

Start the total at zero. Add 4, skip −1, and stop at 0. The final 7 belongs to a different batch, so the result is 4.

Try it yourself

What changes if the input is 4, −1, 7, 0?

Check your answer

Both positive readings arrive before the sentinel. Their sum is 11. An empty sequence yields 0.

A Tour of Go

Related tags

  • Go
  • iteration
  • loop control
  • accumulators