Go Tutorial · Control Flow · Lesson 12 of 30

Go For Loops

Go's only loop: classic for, while-style, infinite loops and range.

One loop to rule them all

Go has only for, which covers every kind of loop:

Example 1
package main

import "fmt"

func main() {
	for i := 0; i < 3; i++ { // classic
		fmt.Print(i, " ")
	}
	fmt.Println()

	n := 1
	for n < 100 { // "while"
		n *= 3
	}
	fmt.Println(n)

	count := 0
	for { // infinite, until break
		count++
		if count == 5 {
			break
		}
	}
	fmt.Println(count)
}

Output

0 1 2 
243
5

Run this on your computer — see “Get Started” for setup.

range

range iterates over slices, arrays, strings, maps, channels — and, since Go 1.22, integers:

Example 2
package main

import "fmt"

func main() {
	langs := []string{"Go", "Rust", "Zig"}
	for i, lang := range langs {
		fmt.Println(i, lang)
	}
	for _, r := range "héy" {
		fmt.Print(string(r), "|")
	}
	fmt.Println()
	for i := range 3 {
		fmt.Print(i, " ")
	}
	fmt.Println()
}

Output

0 Go
1 Rust
2 Zig
h|é|y|
0 1 2 

Run this on your computer — see “Get Started” for setup.

Use _ to ignore the index or value. Map iteration order is random — sort the keys if you need a stable order.

break, continue and labels

Example 3
package main

import "fmt"

func main() {
	outer:
	for i := 1; i <= 3; i++ {
		for j := 1; j <= 3; j++ {
			if j == 2 {
				continue
			}
			if i*j == 3 {
				fmt.Println("found", i, j)
				break outer
			}
			fmt.Println(i, j)
		}
	}
}

Output

1 1
found 1 3

Run this on your computer — see “Get Started” for setup.

Test yourself

How do you write a while loop in Go?

  1. while condition { ... }
  2. for condition { ... }
  3. loop condition { ... }
  4. do { ... } while condition
Show answer

Answer: for condition { ... }