Expression switches
In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a “default” case, its statements are executed. There can be at most one default case and it may appear anywhere in the “switch” statement. A missing switch expression is equivalent to the boolean value true.
ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . ExprCaseClause = ExprSwitchCase ":" StatementList . ExprSwitchCase = "case" ExpressionList | "default" .
There’s a lot packed into that paragraph. But most of it is pretty intuitive, so doesn’t need a lot of special attention.
The main takeaways from this are:
-
cases are evaluated top-to-bottom. This means that if you cases that aren’t completely exclusive of each other, the one listed first takes priority. For example:
switch { case x == 3: /* x is exactly 3 */ case x > 0: /* x is greater than 0, but not 3 */ default: /* x is less than or equal to 0 */ }
-
the location of the
default
case doesn’t matter. This means the following code is equivalent to the previous example:switch { default: /* x is less than or equal to 0 */ case x == 3: /* x is exactly 3 */ case x > 0: /* x is greater than 0, but not 3 */ }
However, I think it’s good practice to put the
default
case at the end, just because it’s easier to comprehend that way.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)