Lesson contents

Go — Continue statements

continue begins the next iteration of a Go for loop. A guard at the top can exclude invalid records before any aggregates change.

A simple example

Skip just the number 2

  1. Start with Visit 1 through 3
  2. Do this Skip 2
  3. Result 1 → 3
Skipping one number still allows the next number to be printed.
main.go
package main

import "fmt"


func main() {
    for n := 1; n <= 3; n++ {
        if n == 2 {
            continue
        }
        fmt.Println(n)
    }
}
Output
1
3
Advertisements

Exclude invalid readings while keeping zero

Skip negative readings, which represent invalid measurements here. Count every valid reading, including zero, and add it to the total. The range iteration advances automatically on continue. A zero passes this guard and counts as a real observation.

Valid intervals: 0, 4, 6. Intervals counted: 3. Total visitors: 10.
Count the quiet interval too

A counter records visitors in each time interval. A negative reading signals a fault, while zero means the counter worked and nobody entered. Keeping 0, 4 and 6 gives three valid intervals and ten visitors.

Run the example

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

go run main.go
main.go
package main

import (
	"fmt"
)

func main() {
	count, sum := 0, 0
	for _, reading := range []int{-2, 0, 4, -1, 6} {
		if reading < 0 {
			continue
		}
		count++
		sum += reading
	}
	fmt.Printf("%d readings, sum %d\n", count, sum)
}
Output
3 readings, sum 10

The valid values are 0, 4, and 6. Skipping the negative entries changes the count without losing the measured zero.

Try it yourself

Append −3 and then 0. What should the count and sum become?

Check your answer

The count rises to 4 and the sum stays 10. Only the appended zero is a valid measurement.

Go language specification

Related tags

  • Go
  • continue
  • filtering
  • loop control