Go Tutorial: Control Flow
Make your program smart. Teach it to make decisions, choose between paths, and react differently to different situations.
Your program needs to think
Until now your programs have been a straight line. Line 1 runs, then line 2, then line 3. No choices. No reactions.
But real programs make decisions. Show this page if the user is logged in. Charge this price if the user has a premium plan. Print a different message depending on the score.
That is control flow — teaching your program when to go left and when to go right.
Twelve steps.
What you'll learn in this Go control flow tutorial
This interactive Go tutorial has 9 hands-on exercises. Estimated time: 18 minutes.
- Your first decision — An `if` statement runs code only when a condition is true. Run this, then change `age` to 15 and run again to see what c…
- Comparison operators — `==`, `!=`, `<`, `>`, `<=`, `>=` — six operators. Change `age` to different values and see which lines print.
- if-else — two paths — `if` runs one path, `else` runs the other. Change `age` to 10, then to 25, and watch which branch runs each time.
- else if — more than two paths — `else if` adds more branches. Change `age` to 4, 9, 14, or 25 — each lands in a different library section.
- Logical operators — combine conditions — `&&` means AND (both must be true), `||` means OR (at least one). Try changing `hasLibraryCard` to `false` and run again…
- switch — membership tiers — `switch` checks one variable against many cases. Change `tier` to "Gold", "Silver", or "Bronze" and run each time.
- Multiple values in one case — Several values can share one case: `case "Overdue", "Lost":`. Add a case that matches both and prints a fine message.
- switch with no condition 🤯 — A `switch` without a variable acts like a clean `if-else` chain. Run this, then try `daysOverdue := 7`.
- Build a decision machine — Write a program with `age`, `itemsBorrowed`, and `hasMembership`. Print "Premium" if items >= 20 AND hasMembership, else…
Go Control Flow concepts covered
- Your program needs to think