Yesterday we looked at if
statements, which allows conditional execution of two branches. And we saw how by chaining else if
we can extend that to an arbitrary number of branches. But there’s often a cleaner way to handle multiple branches:
Switch statements
“Switch” statements provide multi-way execution. An expression or type is compared to the “cases” inside the “switch” to determine which branch to execute.
SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
There are two forms: expression switches and type switches. In an expression switch, the cases contain expressions that are compared against the value of the switch expression. In a type switch, the cases contain types that are compared against the type of a specially annotated switch expression. The switch expression is evaluated exactly once in a switch statement.
Naturally, we’ll be looking at both types over the coming few days. But we’ll start with expression switches as the baseline.
For now, let’s just gently introduce the concept with an example, by re-writing yesterday’s else if
chain into a switch, so we all know what we’re talking about.
Yesterday we saw:
if thing == 1 {
/* ... */
} else if thing == 2 {
/* ... */
} else if thing == 3 {
/* ... */
}
As a switch statement, the same looks like this:
switch thing {
case 1:
/* ... */
case 2:
/* ... */
case 3:
/* ... */
}
Or alternately:
switch {
case thing == 1:
/* ... */
case thing == 2:
/* ... */
case thing == 3:
/* ... */
}
Why would anyone prefer the second form? Well, in this example, you probably wouldn’t. But if you ever need to compare something other than thing
in one of the cases, then this second form can make sense:
switch {
case thing == 1:
/* ... */
case thing == 2:
/* ... */
case thing == 3:
/* ... */
case otherThing == "blue":
/* ... */
case thing == 4 && otherThing = "red":
/* ... */
}
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)