An if chain that checks menu == "Tendon Meatballs", then menu == "Chicken Noodles", then the next dish, grows longer with every new dish, and the name menu is written again on every line. switch tidies it up: it picks one branch by matching one value against a list of cases.
It works just like the price board at Bimo's Meatball Stall. A customer names a dish, Bimo looks for its line from the top, says the price, and that's it. He doesn't go on to read out the price on the next line. If the dish isn't on the board, he says "Not on the menu".
switch on a value
If you come from JavaScript, guess first: the code below has not a single break, and menu holds "Chicken Noodles". How many lines get printed: 1, 2 or 3?
package main
import "fmt"
func main() {
menu := "Chicken Noodles"
switch menu {
case "Tendon Meatballs":
fmt.Println("$15")
case "Chicken Noodles":
fmt.Println("$12")
case "Iced Tea", "Iced Orange":
fmt.Println("$5")
default:
fmt.Println("Not on the menu")
}
}
$12
switch menucomparesmenuwith eachcasefrom top to bottom, like==. The first case that is equal runs.case "Iced Tea", "Iced Orange":a case may hold several values, separated by commas. Matching any one of them is enough.default:runs when no case matches. You may leave it out; with nodefaultand no matching case, the switch does nothing.- Like
if,menuneeds no brackets, and{must sit on the same line.
menu |
Matching case | Printed |
|---|---|---|
"Tendon Meatballs" |
case "Tendon Meatballs" |
$15 |
"Chicken Noodles" |
case "Chicken Noodles" |
$12 |
"Iced Orange" |
case "Iced Tea", "Iced Orange" |
$5 |
"Mixed Ice" |
none, so default |
Not on the menu |
Later, in the Interface lesson, you'll also meet the type switch, which picks by type instead of by value.
Every case stops by itself
In Go, once the matching case's body is done, the switch is done too. You don't need to write break. That's different from C, Java and JavaScript, which without break go on running the body of the case below. So with "Chicken Noodles", only 1 line is printed: $12. Writing break at the end of a case is still allowed, it just does nothing.
fallthrough: carry on into the next case on purpose
If you really do want the next case's body to run too, write fallthrough as the last line of the case:
combo := "full"
switch combo {
case "full":
fmt.Println("+ egg")
fallthrough
case "regular":
fmt.Println("+ meatballs")
case "saver":
fmt.Println("+ broth")
}
+ egg
+ meatballs
fallthroughruns the body of the case right below without checking its value."full"is clearly not"regular", yet+ meatballsis still printed.- It only jumps one case.
+ brothis not printed, because the"regular"case has nofallthrough. - In the very last case,
fallthroughfails to compile:cannot fallthrough final case in switch. - It's rarely used. Several values in one case are usually clearer.
switch with no value: the stand-in for an if-else chain
Remember the bonus from the If Else lesson? That if-else if chain can be written as a switch with no value:
total := 45
switch {
case total >= 50:
fmt.Println("Free iced tea")
case total >= 30:
fmt.Println("Free crackers")
default:
fmt.Println("No bonus yet")
}
Free crackers
switch { with no value means every case holds a condition, and the first case that is true runs. The rest are not checked any more.
total |
>= 50 |
>= 30 |
Printed |
|---|---|---|---|
| 20 | false |
false |
No bonus yet |
| 45 | false |
true |
Free crackers |
| 60 | true |
not checked | Free iced tea |
The order matters. If total >= 30 goes on top, $60 stops there and gets crackers, not iced tea. Also don't put total after switch when the cases hold conditions: switch total { case total >= 30: } fails to compile with cannot convert total >= 30 (untyped bool value) to type int, because every case is compared with total, which is a number.
⚠️ What makes a switch run differently than you thought
breakinside a switch, inside a for. Thatbreakonly leaves the switch, not the loop, so the next round still runs. To leave the loop, use anifwithbreakoutside the switch.- The order of cases in a switch with no value. Put the narrowest condition (
>= 50) on top. - Thinking
fallthroughchecks the next case. It doesn't: the body just runs. - The same value in two cases. Go rejects it at compile time:
duplicate case "Tendon Meatballs" (constant of type string) in expression switch.
To leave the loop right from inside a case, give the loop a label (a name followed by a colon above the for), then write break with that name:
queue:
for number := 1; number <= 5; number++ {
switch number {
case 3:
break queue
}
fmt.Println("number", number)
}
fmt.Println("done")
number 1
number 2
done
Without the label, break in case 3 only leaves the switch, so number 3 to number 5 still print. Other options:
| Way | When to pick it |
|---|---|
break queue with a label |
The decision to leave is inside a case. This is the usual way in Go. |
return |
The loop is in its own function and nothing else runs after the loop. |
if with break outside the switch |
The condition is simple and can be checked without the switch. |
TL;DR: switch value { case a: ... case b, c: ... default: ... } compares the value with each case from the top, and only the first matching case runs. In Go every case stops by itself, no break needed. fallthrough deliberately runs the next case's body without checking its value. switch { case condition: ... } with no value stands in for an if-else chain: the first true case wins, so the order matters.
⚡ One value, many cases
Write:
switch menu {
case "Tendon Meatballs":
fmt.Println("$15")
case "Chicken Noodles":
fmt.Println("$12")
case "Iced Tea", "Iced Orange":
fmt.Println("$5")
default:
fmt.Println("Not on the menu")
}
Meaning: menu is compared with each case from the top, like ==. One case can hold several values separated by commas, and default runs when none matches.
⚡ No break needed
Guess first: menu holds "Chicken Noodles" and there isn't a single break. How many lines print?
One: $12. In Go every case stops by itself, unlike C, Java and JavaScript.
Meaning: Want to carry on into the case below? Write fallthrough as that case's last line. The next case's body runs without its value being checked.
⚡ A switch with no value
Write:
switch {
case total >= 50:
fmt.Println("Free iced tea")
case total >= 30:
fmt.Println("Free crackers")
default:
fmt.Println("No bonus yet")
}
Meaning: Every case holds a condition, and the first case that is true wins. Put the narrowest condition on top.