The Multi-case switch Statement
A single case in a switch isn't limited to one value. List several, separated by commas, and the block runs when the expression equals any of them.
Multi-case switch Syntax
main.go
switch expression {
case x,y:
// code block if expression is evaluated to x or y
case v,w:
// code block if expression is evaluated to v or w
case z:
...
default:
// code block if expression is not found in any cases
}
Multi-case switch Example
Here the day number decides which message gets printed: odd weekdays, even weekdays and the weekend each share a case. Since day is 5, it matches case 1,3,5.
Example
Prompt
Use a multi-case switch with day set to 5. Group odd weekdays (1,3,5), even weekdays (2,4), and weekend (6,7) into separate cases with a default.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
day := 5
switch day {
case 1,3,5:
fmt.Println("Odd weekday")
case 2,4:
fmt.Println("Even weekday")
case 6,7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day of day number")
}
}