Conditions and loops

if / else, switch, and for — Go's only loop — with a counter, a condition or range.

Runs in Zerethon IDE · Go 1.27 Official Go documentation ↗
main.go
package main

import "fmt"

func main() {
	for n := 1; n <= 5; n++ {
		if n%2 == 0 {
			fmt.Println(n, "even")
		} else if n == 5 {
			fmt.Println(n, "last")
		} else {
			fmt.Println(n, "odd")
		}
	}

	i := 3
	for i > 0 {
		i--
		if i == 1 {
			continue
		}
		fmt.Println("i =", i)
	}

	for index, fruit := range []string{"apple", "pear"} {
		fmt.Println(index, fruit)
	}

	switch day := 6; day {
	case 0, 6:
		fmt.Println("weekend")
	default:
		fmt.Println("weekday")
	}
}

Output

1 odd
2 even
3 odd
4 even
5 last
i = 2
i = 0
0 apple
1 pear
weekend
  • There is no while: for condition { } is the while loop, and for { } loops forever until break.
  • No parentheses around the condition, but braces are always required.
  • range gives the index and the value of a slice, the key and value of a map, or for i := range 10 counts 0 to 9.
  • A switch case does not fall through to the next one; no break needed.