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 12 hands-on exercises. Estimated time: 18 minutes.
- Your first decision — Imagine a bouncer at a club. They check your age. If you are old enough — you get in. If not — you don't.
- Comparison operators — The condition inside an `if` uses comparison operators to check relationships between values.
- if-else — two paths — An `if` runs code when the condition is true. But what about when it is false?
- else if — more than two paths — Sometimes two options are not enough. What if you need A, B, C, D, or F?
- Logical operators — combine conditions — Sometimes one condition is not enough. What if you need two things to be true at the same time?
- switch — cleaner decisions — When you have one variable and many possible values, a long `else if` chain gets messy fast.
- Multiple values in one case — Sometimes several different values should do the same thing.
- switch with no condition — A `switch` does not need a variable to compare. Without one, each case acts like an `if` condition.
- Short variable declaration in if — Go lets you declare a variable right inside the `if` statement.
- Nested if — a decision inside a decision — Sometimes you need to check one thing, and only if that passes, check something else.
- Fix the broken logic — This program is supposed to check if someone can drive.
- Build a decision machine — No starter code.
Go Control Flow concepts covered
- Your program needs to think