Back to Concepts Roadmap
🟠 Level 2 — Flow Control
Flow Control

Conditionals

Branching logic using if, else, and Go unique short initializer statements.

Real-World Analogy (Mental Model)

Think of a train track switch that checks the signal right before switching tracks. Go allows you to prepare the signal (initializer) on the exact same line as the switch.

Architecture & Memory MapVisual Model
if [init statement]; [condition check] {
    // executes if true
} else {
    // executes if false
}

Key Concepts & Rules To Remember

  • No parentheses required around condition checks: `if x > 10 { ... }`.
  • Short initializer syntax: `if err := doWork(); err != nil` limits variable scope to the if-block.
  • Go encourages early returns and guard clauses over deeply nested if-else trees.
Step-by-Step Code

1. Scoped Initializer Statements

You can execute a statement before checking a condition. Variables created here exist only inside the if-else blocks, preventing namespace pollution.

example.goGo 1.24+
if user, err := findUser(101); err != nil {
    fmt.Println("Error:", err)
    return
} else {
    fmt.Println("Found user:", user.Name)
}
// 'user' is no longer accessible here! Kept safe from accidental reuse.

Common Beginner Pitfalls & Mistakes

Mistake: Writing giant nested if/else pyramids.
✅ Correct Way: Use "guard clauses" (check for error, return immediately) to keep happy-path code left-aligned.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

Where is a variable declared in an `if err := do(); err != nil` statement accessible?

Finished this lesson?

Mark it as complete to track your overall Go mastery.