Expression switch statements
While it’s possible to add as many else if
statements to an if
statement as you want, at some point, it’ll get hard to read.
When this happens, you can use Go’s logic alternative: switch
. For situations where you would need a big if
statement, switch
can be a more compact alternative.
The notation for switch
is shown in the following code snippet:
switch <initial statement>; <expression> { case <expression>: <statements> case <expression>, <expression>: <statements> default: <statements> }
The initial statement works the same in switch
as it does in the preceding if
statements. The expression is not the same because if
is a Boolean expression. You can have more than just a Boolean in this expression. The cases
are where you check to see whether the statements get executed. Statements are like code blocks in if
statements, but with no need...