Switch
A switch picks one branch among many cases.
Think of it as a multiple-choice question.
In Go, cases do not fall into the next one by default.
Each case ends on its own unless you write fallthrough.
Switch on a value
Match a value against several options.
Use default for everything else.
One case can list several values separated by commas.
Switch without an expression
If you leave out the expression, it is like switch true.
Each case is a true/false check.
This is a clean way to replace a long else-if chain.
Short statement
Like if, switch can start with a short declaration.
That temporary name only lives inside the switch.
fallthrough
Use fallthrough only when you really want the next case to run too.
Most of the time you do not need it.
Why Go's switch feels safe
By default, one matching case runs, then switch exits.
There is no accidental fallthrough.
One matching case runs, then switch exits, unless you ask for fallthrough.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.