Control Flow: if, for, and switch
Go's single looping construct, condition-only if statements, and switch.
What you'll learn
- Write a `for` loop in Go's three common forms (counting, condition-only, infinite)
- Write `if`/`else if`/`else` without requiring parentheses around the condition
- Use `switch` without needing an explicit `break` in each case
Explanation
Go has exactly one looping keyword: for. It covers every loop shape other languages split across for/while/do-while: a counting loop (for i := 0; i < n; i++), a condition-only loop (for condition, like a while), and an infinite loop (for {}, exited with break).
if conditions never need parentheses (if x > 0 { ... }, not if (x > 0)), and the opening brace must be on the same line as the condition -- Go's formatting rules aren't just style preference here, they're enforced by the compiler's parsing rules.
Go's switch does not fall through to the next case by default (unlike C, Java, or JavaScript) -- each case automatically breaks after its own block, so you don't need an explicit break statement. If you genuinely want fallthrough behavior, you opt in explicitly with the fallthrough keyword.
Guided lab
Fill in the blank: FizzBuzz-style loop
Fill in the missing loop keyword, then predict the output.
package main
import "fmt"
func main() {
____ i := 1; i <= 5; i++ {
if i%2 == 0 {
fmt.Println(i, "even")
} else {
fmt.Println(i, "odd")
}
}
}Stuck? Get a hint.
Common mistakes
- Adding parentheses around an `if`/`for` condition out of habit from another language -- Go allows this to compile in some forms but it's not idiomatic and can cause confusion with more complex conditions.
- Expecting a `switch` case to fall through to the next case by default, forgetting Go breaks automatically after each case.
- Forgetting Go has no `while` keyword -- a condition-only `for` is how you write what other languages call a while loop.
Knowledge check
Takeaway
Go has one loop keyword (`for`, in three forms) and a `switch` that never falls through unless you explicitly ask for it with `fallthrough`.
Summary
`for` covers every loop shape Go needs; `if`/`else` needs no parentheses; `switch` cases break automatically after each case.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.