TExcelTAD
Home › Go › Go For Loops

Go For Loops

Go has exactly one loop keyword: for. There is no while and no do … while — for covers every looping style just by leaving out parts of its header.

Form Looks like Use it for
Three-part for i := 0; i < n; i++ { } counting
Condition only for x < 100 { } "while" loops
Infinite for { } servers, retry loops — exit with break or return
Range for i, v := range items { } walking over collections (next chapter)
Integer range for i := range 5 { } counting 0…4 (Go 1.22+)

The three-part loop

The header has an init statement, a condition and a post statement, separated by semicolons. No parentheses, and the braces are mandatory.

go · try it yourself
package main

import "fmt"

func main() {
	for i := 1; i <= 5; i++ {
		fmt.Println("Lap", i)
	}

	for countdown := 10; countdown > 0; countdown -= 3 {
		fmt.Print(countdown, " ")
	}
	fmt.Println("liftoff!")
}
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
10 7 4 1 liftoff!
  1. i := 1 runs once, before the loop starts.
  2. i <= 5 is checked before every iteration; the loop stops when it is false.
  3. i++ runs after every iteration.

The "while" loop

Drop the init and post statements (and their semicolons) and you have a while loop.

go · try it yourself
package main

import "fmt"

func main() {
	savings := 1000.0
	years := 0

	for savings < 2000 {
		savings *= 1.07 // 7% interest
		years++
	}
	fmt.Printf("Doubled after %d years: %.2f\n", years, savings)
}
Doubled after 11 years: 2104.85

Infinite loops with break

for { } loops forever. Use break to leave it when a condition is met.

go · try it yourself
package main

import "fmt"

func main() {
	n := 27
	steps := 0
	for {
		if n == 1 {
			break
		}
		if n%2 == 0 {
			n /= 2
		} else {
			n = 3*n + 1
		}
		steps++
	}
	fmt.Println("Collatz steps for 27:", steps)
}
Collatz steps for 27: 111

continue

continue skips the rest of the current iteration and jumps to the next one.

go · try it yourself
package main

import "fmt"

func main() {
	for i := 1; i <= 10; i++ {
		if i%3 != 0 {
			continue
		}
		fmt.Println(i, "is divisible by 3")
	}
}
3 is divisible by 3
6 is divisible by 3
9 is divisible by 3

Nested loops and labels

Loops can be nested. A plain break only exits the innermost loop. To exit an outer loop, put a label before it and write break label (or continue label).

go · try it yourself
package main

import "fmt"

func main() {
	// multiplication table
	for row := 1; row <= 3; row++ {
		for col := 1; col <= 4; col++ {
			fmt.Printf("%3d", row*col)
		}
		fmt.Println()
	}

	// find the first pair that sums to 10
	nums := []int{3, 8, 4, 6, 2}
search:
	for i := 0; i < len(nums); i++ {
		for j := i + 1; j < len(nums); j++ {
			if nums[i]+nums[j] == 10 {
				fmt.Println("pair:", nums[i], nums[j])
				break search
			}
		}
	}
}
  1  2  3  4
  2  4  6  8
  3  6  9 12
pair: 8 2

Ranging over an integer

Since Go 1.22, for i := range n counts from 0 to n-1. It is a short way to repeat something n times.

go · try it yourself
package main

import "fmt"

func main() {
	for i := range 3 {
		fmt.Println("attempt", i)
	}
	for range 2 {
		fmt.Println("beep")
	}
}
attempt 0
attempt 1
attempt 2
beep
beep

Note: Since Go 1.22 each loop iteration gets its own copy of the loop variable. Older Go versions shared one variable across iterations, which caused famous bugs with closures and goroutines.

Test yourself

How do you write a while loop in Go?

  1. while x < 10 { }
  2. for x < 10 { }
  3. loop x < 10 { }
  4. do { } while x < 10

What does continue do?

  1. Exits the loop
  2. Skips to the next iteration
  3. Restarts the loop from the beginning
  4. Pauses the program

How many times does for i := range 4 { } run?

  1. 3
  2. 4
  3. 5
  4. It does not compile