Go switch Statement
The switch statement in Go is a powerful control flow construct
used to select one of many code blocks for execution. It provides a cleaner
and more readable alternative to writing multiple
if...else if conditions.
Unlike languages such as C, C++, or Java, Go’s switch executes only the
first matching case by default—meaning you do not need a
break statement.
Basic Syntax of switch
switch expression { case value1: // code block case value2: // code block
case value3: // code block default: // code block (optional) }
How the switch Statement Works
- The expression is evaluated once.
- Its result is compared against each case value.
- When a match is found, the corresponding block of code is executed.
- Only the first matching case runs.
-
The
defaultblock executes if no match is found (optional but recommended).
Example 1: Displaying Day Name
Example 2: Using the default Case
The default case acts as a fallback when no other case matches.
Key Features of Go switch
-
No need for
breakstatements (automatic termination after a match). -
Supports multiple values in a single case (e.g.,
case 1, 2, 3:). -
The
defaultcase is optional but improves robustness. -
Cleaner and more readable than long
if...else ifchains.
Go Multi-Case switch
In Go, the switch statement becomes even more powerful when you
assign multiple values to a single case. This feature allows you to group
conditions and execute the same block of code for different matching
values—making your code cleaner and more concise.
Syntax of Multi-Case switch
switch expression { case value1, value2: // executes if expression matches
value1 OR value2 case value3, value4: // executes if expression matches
value3 OR value4 default: // executes if no case matches }
How It Works
- The expression is evaluated once.
- Each case can contain multiple comma-separated values.
- If the expression matches any value within a case, that block is executed.
- Only the first matching case runs.
-
The
defaultblock handles unmatched values.
