↓ Skip to main content

Control Flow in Go: if, switch and for

638 words·3 mins· loading · loading ·
Table of Contents
Learn Golang - This article is part of a series.
Part 8: This Article

Updated 16 Nov 2026: rewritten. This version adds the if init statement, expressionless switch, labelled loops and defer ordering, and notes that map iteration order is random.

Control flow decides which statements run and how many times. Go keeps it small: if, switch, one loop keyword (for), and defer. Parentheses around conditions aren’t used, but the braces are mandatory.

if
#

Go
age := 18

if age >= 18 {
	fmt.Println("You are an adult.")
} else if age >= 13 {
	fmt.Println("You are a teenager.")
} else {
	fmt.Println("You are a child.")
}

An if can start with a short statement before the condition. A variable declared there lives only inside the if and its else branches, which keeps error handling tidy:

Go
if n, err := strconv.Atoi("42"); err != nil {
	fmt.Println("not a number:", err)
} else {
	fmt.Println("got", n)
}

switch
#

switch compares a value against a list of cases and runs the first match. Unlike C, Go doesn’t fall through to the next case, so you don’t write break after each one:

Go
day := "Wednesday"

switch day {
case "Monday":
	fmt.Println("It's the start of the week.")
case "Saturday", "Sunday":
	fmt.Println("It's the weekend.")
case "Wednesday":
	fmt.Println("It's the middle of the week.")
default:
	fmt.Println("It's another weekday.")
}
It's the middle of the week.

A case can list several values, as "Saturday", "Sunday" does. A switch with no value after the keyword acts like a neat chain of if statements:

Go
score := 72

switch {
case score >= 90:
	fmt.Println("A")
case score >= 70:
	fmt.Println("B")
default:
	fmt.Println("C")
}
B

If you do want to fall through to the next case, use the fallthrough keyword. It’s rare.

for
#

for is Go’s only loop keyword, and it takes several forms.

Three-part loop, like C:

Go
for i := 1; i <= 3; i++ {
	fmt.Println(i)
}

Condition only, which is what other languages call while:

Go
n := 1
for n <= 3 {
	n *= 2
}
fmt.Println(n) // 4

Infinite loop, ended with break or return:

Go
count := 0
for {
	count++
	if count >= 3 {
		break
	}
}
fmt.Println(count) // 3

Range, which walks over a slice, array, string, map or channel:

Go
numbers := []int{10, 20, 30}

for index, value := range numbers {
	fmt.Println(index, value)
}
0 10
1 20
2 30

Use _ to ignore the index or value you don’t need: for _, value := range numbers. Since Go 1.22 you can also range over an integer, as in for i := range 3, which counts from 0 to 2.

Ranging over a map gives its keys and values in random order, and the order changes between runs. If you need a stable order, collect the keys, sort them, and loop over the sorted keys.

break and continue
#

break leaves the loop. continue skips to the next iteration:

Go
for i := 1; i <= 5; i++ {
	if i == 2 {
		continue // skip 2
	}
	if i == 4 {
		break // stop before 4
	}
	fmt.Println(i)
}
1
3

In nested loops, break and continue apply to the innermost loop. To act on an outer one, put a label in front of it:

Go
outer:
for i := 0; i < 3; i++ {
	for j := 0; j < 3; j++ {
		if j == 2 {
			continue outer
		}
		fmt.Println(i, j)
	}
}

defer
#

defer schedules a function call to run when the surrounding function returns, whichever way it returns. Deferred calls run in last-in, first-out order:

Go
func main() {
	defer fmt.Println("deferred first")
	defer fmt.Println("deferred second")
	fmt.Println("body")
}
body
deferred second
deferred first

Its everyday use is cleanup that must happen no matter what, such as closing a file straight after opening it:

Go
f, err := os.Open("data.txt")
if err != nil {
	return err
}
defer f.Close()

Next: arrays.

Learn Golang - This article is part of a series.
Part 8: This Article

Related