The switch-case Construct
Explore how to implement the switch-case construct in Go to handle multiway branches. Understand its syntax, value and condition testing, initialization within switch, and the use of fallthrough and default cases to control execution flow effectively.
We'll cover the following...
Introduction
In the last two lessons, we studied the if-else construct. There is another control structure known as the switch-case structure.
The keyword switch is used instead of long if statements that compare a variable to different values. The switch statement is a multiway branch statement that provides an easy way to transfer flow of execution to different parts of code based on the value. The following figure explains the basic structure of the switch-case construct.
switch statement with values
Compared to the C and Java languages, switch in Go is considerably more flexible. It takes the general form:
switch var1 {
case val1:
...
case val2:
...
default:
...
}
Where var1 is a variable which can be of any type, and val1, val2, … are possible values of var1. These don’t need to be constants or integers, but they must have the same type, or expressions evaluating to that type.
The opening { has to be on the same line as the switch. The ellipses ... here means ...