Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 147 ยท Operators and Control Flow

for Loops

Learn Go's single loop keyword - the three-clause for, while-style and infinite loops, range over integers, break and continue, and the per-iteration loop variables introduced in Go 1.22.

Go has exactly one loop keyword: for. There is no while, no do ... while and no foreach. The one keyword takes several shapes, from the classic counting loop to a condition-only loop, an endless loop, and a loop over a range of values. Once you know the shapes, you can express every kind of repetition.

This lesson covers each form, break and continue, the range form for integers (added in Go 1.22), and an important Go 1.22 change: every iteration gets its own copy of the loop variable, which fixed one of the most famous bugs in older Go code. Looping over slices, maps, strings and functions with range is the topic of the next lesson, Ranging Over Collections.

The three-clause loop

The classic form has an init statement, a condition and a post statement, separated by semicolons. There are no parentheses, and the braces are required.

Go
for init; condition; post {
	body
}

Go runs init once, then repeats: check condition, run the body, run post. The loop ends when the condition is false. A variable declared in init belongs to the loop.

Go Counting loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last loop shows a Go idiom: because ++ is a statement and not an expression (see Operators), the post statement for two variables uses a tuple assignment, i, j = i+1, j-1. All three parts of the header are optional, which gives us the other forms.

While-style and infinite loops

Drop the init and post statements and you have a loop that only has a condition: Go's while. Drop the condition as well and you have an endless loop that only stops via break, return, panic or the program exiting.

Go The while-style and infinite forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

There is no do ... while. The for { ... if !cond { break } } shape above is the standard replacement: the body runs once before the first test. Endless for {} loops are everywhere in servers, workers and event loops, where the loop ends only when something external tells it to.

range over an integer

Since Go 1.22, range accepts an integer n and counts from 0 up to n-1. It replaces the most common three-clause loop with something shorter and harder to get wrong (no off-by-one in the condition, no way to forget the increment).

Go range over an integer (Go 1.22)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

When the number is a variable, the type of the loop variable is that variable's type (uint8 above). The expression after range is evaluated once, before the loop starts, so changing the number inside the body does not change how many times the loop runs. Use the three-clause form when you need a step other than 1 or a start other than 0.

break and continue

break leaves the innermost loop immediately. continue skips the rest of the current iteration and moves on to the next one (in a three-clause loop, it still runs the post statement first).

Go break and continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

To break out of a nested loop in one step, name the outer loop with a label; see Labels, break, continue and goto.

Per-iteration loop variables (Go 1.22)

Before Go 1.22, a for loop created one variable for the whole loop, and every iteration updated it. Closures or goroutines that captured the variable all saw the same final value, a bug that bit nearly every Go programmer:

Go
// Go 1.21 and earlier: all three functions print 3
for i := 0; i < 3; i++ {
	funcs = append(funcs, func() { fmt.Println(i) })
}

Since Go 1.22, each iteration has its own i, so the code above now prints 0, 1, 2. The new rule applies to modules whose go.mod says go 1.22 or later, which is true for every new project. Both forms are shown below. The second loop reproduces the old behavior on purpose by declaring i once outside the loop, so all closures share it.

Go Per-iteration variables versus one shared variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first line prints 0 1 2, the second prints 3 3 3 because every closure reads the same j after the loop finished, and the last line prints true true. With per-iteration variables, taking &i inside a loop is safe too.

How does this work for the three-clause form, where the post statement increments i? At the end of each iteration Go copies the current value into a fresh variable for the next iteration and applies the post statement to the copy. If the body changes i (for example i += 2), the change carries over to the next iteration, so loops that skip ahead still behave as you expect.

Per-iteration variables are tied to the language version in go.mod. If you maintain an old module that declares go 1.21 or earlier, loops there still share one variable until you update the go line. Modules are covered in Go Modules.

Common loop mistakes

  • Off-by-one errors. i <= len(s) instead of i < len(s) reads one element past the end and panics. for i := range len(s) and for i := range s avoid the problem.
  • Forgetting to update the condition in a while-style loop produces an endless loop. Check that something in the body moves the loop toward its exit.
  • Modifying a slice while iterating over it by index. Compute the length once or build a new slice. The next lesson shows what range does in this case.
  • Floating-point loop counters. for x := 0.0; x != 1.0; x += 0.1 never reaches exactly 1.0. Count with an integer and compute the float from it.
Go Why not to count with floats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which keyword creates a while-style loop in Go?

    for is the only loop keyword. A for with just a condition (for n > 0 {) acts as while.
  2. 2. How many times does for i := range 3 { ... } run, and what values does i take?

    Since Go 1.22, range over an integer n counts from 0 to n-1.
  3. 3. In Go 1.22 or later, what does this print? var fs []func() int; for i := 0; i < 3; i++ { fs = append(fs, func() int { return i }) }; for _, f := range fs { fmt.Print(f(), " ") }

    Each iteration has its own copy of i, so each closure remembers the value from its own iteration.
  4. 4. How do you write a loop that runs its body at least once and stops when done is true?

    Go has no do-while. An endless for loop with a conditional break at the end of the body does the same job.
  5. 5. What does continue do in the body of a three-clause for loop?

    continue jumps to the end of the current iteration. The post statement and the condition still run before the next iteration.

Summary

  • for is Go's only loop keyword and comes in four shapes: three-clause, condition-only (while), endless (for {}) and range.
  • for i := range n (Go 1.22) counts from 0 to n-1; for range n repeats without a counter.
  • Use break to leave the innermost loop and continue to start the next iteration. Labels reach outer loops.
  • Emulate do ... while with an endless loop and a conditional break.
  • Since Go 1.22 every iteration has its own loop variable, so closures, goroutines and &i capture the value you expect.
  • Count with integers, not floats, and prefer range over index arithmetic to avoid off-by-one errors.

Next: Ranging Over Collections