Stage 1 · Code
Variables, Types & Control Flow
if and switch
Write conditional logic in Go with concise if statements, initialization clauses, and expressive switch expressions.
Basic if
An if statement in Go runs a block of code only when a boolean expression is true. The condition does not need parentheses, but the body must be wrapped in curly braces — even for a single line.
Go does not treat zero, empty string, or nil as false. You must write an explicit comparison: if len(s) == 0, if n != 0, if ptr != nil. This removes an entire class of subtle bugs found in C or JavaScript.
if / else if / else Chains
When you have more than two outcomes, chain conditions with else if. Only the first true branch runs; the rest are skipped. A final else is a catch-all for everything the earlier conditions missed.
When the happy path is one condition among many error cases, check errors first and return early. This keeps the main logic at the outermost indent level and makes functions easier to read from top to bottom.
Initialization Clause
Go's if statement supports an optional initialization clause before the condition. It declares a variable that exists only inside the if block (and any else block). This scopes temporary values exactly where they are needed.
switch Statements
A switch statement is a cleaner alternative to a long else if chain. Each case is tested in order; the first match runs and the switch ends. Unlike C or Java, Go does not fall through to the next case by default.
fallthrough and Multi-Case
When you explicitly need the next case to run after a matching case, use the fallthrough keyword. It transfers control unconditionally to the start of the next case — not its condition, but its body.
Just like if, switch also accepts an initialization clause: switch n := computeValue(); { case n > 0: ... }. This scopes the temporary variable n to the switch block only.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.