๐Ÿ”€Control FlowLESSON

Control Flow

Go provides a clean, minimal set of control flow constructs. If you're coming from another language, you'll find them familiar but with a few Go-specific twists.

if / else if / else

Go's if statement does not require parentheses around the condition โ€” in fact, gofmt will remove them if you add them.

Go also supports an optional init statement before the condition, separated by a semicolon. The variable declared there is scoped to the entire if/else block:

This pattern is common when calling a function that returns a value you only need within the conditional.

switch

switch in Go is cleaner than long chains of if/else. Unlike C or Java, cases do not fall through automatically โ€” each case breaks implicitly after executing.

A single case can match multiple values by separating them with commas. The default branch is optional.

If you genuinely need fallthrough behavior, the fallthrough keyword exists โ€” but it is rare and considered a code smell in most situations. Prefer explicit logic over relying on fallthrough.

Go also supports expression-less switch, which acts like a cleaner if/else if chain:

for โ€” the only loop keyword

Go has exactly one loop keyword: for. There is no while, do/while, or repeat. The three forms cover every use case.

C-style loop:

While-style loop (omit init and post statements):

Infinite loop (omit everything, use break to exit):

You can also use continue to skip the rest of the current iteration, and labeled break or continue to target an outer loop.

for range

The range clause iterates over slices, arrays, strings, maps, and channels.

Here i is the index and v is the value. Use the blank identifier _ to discard whichever you don't need:

For maps, range yields key-value pairs. For strings, range yields the byte index and the Unicode rune at that position โ€” which handles multi-byte characters correctly.

Knowledge Check

In a Go switch statement, what happens after a matching case executes?

When using `for i, v := range slice`, what is `i`?

How do you write a while-style loop in Go?