Fundamentals

Control Statements

Control the flow of a program with for, if, switch, break, continue, and defer.

What you will learn

Control flow decides which statements run, how many times, and when execution leaves a block. This lesson covers Go's single loop keyword for in all its forms, if and switch for decisions, break and continue for steering loops, and defer for running cleanup code when a function ends.

The for loop

Go has exactly one loop keyword, for. Where other languages use while and do-while, Go reuses for.

The three-part loop

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

It has three parts, separated by semicolons:

PartExampleRuns
Initi := 0Once, before the loop starts
Conditioni < 5Before every pass; the loop stops when it is false
Posti++After every pass

This prints 0 1 2 3 4. The variable i exists only inside the loop. There are no parentheses around the three parts, but the braces are required.

Condition only (Go's while)

Drop the init and post parts and keep the condition:

sum := 1
for sum < 1000 {
    sum += sum
}
fmt.Println(sum) // 1024

Infinite loop

Drop everything and the loop runs until you leave it with break or return:

for {
    fmt.Println("waiting for work...")
    break // without this it would run forever
}

Servers use this form constantly, because they must keep listening for requests.

Looping over a collection with range

range walks over slices, arrays, strings, and maps, giving you the position and the value:

names := []string{"Ada", "Grace", "Linus"}

for index, name := range names {
    fmt.Println(index, name)
}
0 Ada
1 Grace
2 Linus

Use _ to ignore the index or the value you do not need:

for _, name := range names {
    fmt.Println(name)
}

Since Go 1.22, you can also range over a whole number to repeat something that many times:

for i := range 3 {
    fmt.Println(i) // 0, 1, 2
}

if and else

score := 85

if score >= 90 {
    fmt.Println("Grade: A")
} else if score >= 75 {
    fmt.Println("Grade: B")
} else {
    fmt.Println("Grade: C")
}

Go has no parentheses around the condition and always requires braces. The condition must be a bool, so if score { with an integer does not compile.

else must sit on the same line as the closing brace of the previous block (} else {). Go inserts semicolons at line ends, so putting else on its own line is a syntax error. The formatter handles this for you.

if with a short statement

You can run a short statement before the condition, separated by a semicolon:

if total := 50 * 3; total > 100 {
    fmt.Println("free shipping, total was", total)
} else {
    fmt.Println("add more items, total was", total)
}
// total does not exist out here

The variable total is visible in the if and in every else branch, and disappears afterwards. This keeps temporary values from leaking into the rest of the function, and it is the common shape for error checks:

if err := doWork(); err != nil {
    return err
}

switch

A switch compares one value against several cases and is cleaner than a long chain of else if:

region := "US-East"

switch region {
case "US-East", "US-West":
    fmt.Println("routing to North America")
case "EU-Central":
    fmt.Println("routing to Europe")
default:
    fmt.Println("routing to the global fallback")
}

Three things make Go's switch different from C or Java:

  1. No fall-through. Only the matching case runs, so you do not write break. (If you really want to continue into the next case, the fallthrough keyword does it, but it is rarely needed.)
  2. A case can list several values, separated by commas.
  3. Cases need not be constants. They can be any expressions.

Switch with no value

A switch without a value checks each case as a condition, and runs the first one that is true. It reads better than a long if/else chain:

temperature := 31

switch {
case temperature >= 35:
    fmt.Println("very hot")
case temperature >= 25:
    fmt.Println("warm")
default:
    fmt.Println("cool")
}

A switch can also begin with a short statement, just like if: switch day := today(); day { ... }.

break and continue

  • break leaves the nearest for, switch, or select immediately.
  • continue skips the rest of the current pass and moves to the next one.
for i := 1; i <= 10; i++ {
    if i == 3 {
        continue // skip 3
    }
    if i == 7 {
        break // stop at 7
    }
    fmt.Println(i)
}

This prints 1, 2, 4, 5, 6.

When loops are nested, break only leaves the inner one. A label lets you leave the outer one:

outer:
for row := 0; row < 3; row++ {
    for col := 0; col < 3; col++ {
        if row == 1 && col == 1 {
            break outer
        }
        fmt.Println(row, col)
    }
}

Labels are uncommon, so reach for them only when the alternative is clumsier.

defer

defer schedules a function call to run when the surrounding function finishes, however it finishes. Its most important use is cleanup, such as closing a file:

func readConfig(path string) error {
    file, err := os.Open(path)
    if err != nil {
        return err
    }
    defer file.Close() // runs when readConfig returns, on any path

    // ... read from file ...
    return nil
}

Placing defer file.Close() right after opening the file means you cannot forget to close it, even if you add more return statements later.

Two rules explain how defer behaves:

  1. The arguments are evaluated immediately, when the defer line runs, but the call itself waits.
  2. Deferred calls run in last-in, first-out order, like a stack of plates.
func main() {
    fmt.Println("starting")

    for i := 1; i <= 3; i++ {
        defer fmt.Println("deferred", i)
    }

    fmt.Println("done")
}
starting
done
deferred 3
deferred 2
deferred 1

Each defer captured its value of i at the time it ran. Then, when main finished, the calls ran in reverse. You can read more in the Go blog post Defer, Panic, and Recover.

Common mistakes

  • Writing parentheses or omitting braces out of habit from other languages.
  • Putting else on a new line. It must follow the closing brace.
  • Expecting switch to fall through. Each case ends on its own.
  • Using defer inside a long loop to close many files. Deferred calls only run when the function returns, so the files stay open until then. Close them inside a helper function instead.
  • Forgetting that break inside a switch inside a for leaves the switch, not the loop.

Practice

Write a loop that examines the numbers from 1 to 30. Print Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both. Print the number itself otherwise.

Summary

Go has one loop keyword, for, which covers counted loops, condition-only loops, infinite loops, and range over collections. if and switch need no parentheses, can start with a short statement that stays scoped to them, and switch cases do not fall through. break and continue steer loops, with labels available for nested ones. defer runs a call when the surrounding function ends, with arguments evaluated immediately and calls running in last-in, first-out order, which makes it ideal for cleanup.

Official reference: A Tour of Go: Flow control statements.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026