Understand the contract

Go uses for for ordinary loops. You can supply an initializer, condition and update, write only a condition, or omit all three for an indefinite loop. Choose a form that makes the stopping condition visible. A loop that processes a slice usually works well with range, covered later.

break exits the innermost enclosing for, switch or select. continue skips to the next iteration of the enclosing loop. In a three-part for, the update statement still runs after continue. In a condition-only loop, you must arrange any progress yourself, or a skipped update can cause an infinite loop.

Work through the example

The example adds the odd integers from one through five and prints 9. The <= condition includes the upper boundary. Using < would exclude five. The counter is scoped to the loop, while sum belongs to the enclosing function so it remains available after iteration ends.

package main

import "fmt"

func main() {
    sum := 0
    for i := 1; i <= 5; i++ {
        if i%2 == 0 { continue }
        sum += i
    }
    fmt.Println(sum)
}

Watch this boundary

An indefinite loop is appropriate only when another event can terminate it, such as an input error or cancellation. A busy loop that repeatedly checks a flag wastes CPU and may introduce a race. Later lessons use blocking channel operations and context cancellation to wait for concurrent work.

Practice with a changed input

Change the upper limit to zero and predict the sum. Then rewrite the example as a condition-only loop while preserving the behavior of continue.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services