The switch statement selects and executes one code block from multiple possible options based on the value or type of an expression. It provides a cleaner alternative to multiple if-else statements and supports both value-based and type-based branching. Go supports two types of switch statements:
- Expression Switch
- Type Switch
Example: The following code prints the day of the week based on the value of day.
package main
import "fmt"
func main() {
day := 4
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
default:
fmt.Println("Invalid day")
}
}
Output
Thursday
Expression Switch
An expression switch evaluates an expression and executes the matching case block.
Example: The following example determines whether a number is positive, negative, or zero.
package main
import "fmt"
func main() {
num := -5
switch {
case num > 0:
fmt.Println("Positive")
case num < 0:
fmt.Println("Negative")
default:
fmt.Println("Zero")
}
}
Output
Negative
Explanation:
- switch without an expression behaves as switch true.
- Each case contains a boolean condition.
- num < 0 evaluates to true, so "Negative" is printed.
- default executes only if none of the conditions match.
Syntax
switch initialization; expression {
case value1:
// Code block
case value2:
// Code block
default:
// Code block
}
Components:
- initialization: Optional statement executed before the switch evaluation.
- expression: Value used for comparison.
- case: Defines matching conditions.
- default: Executes when no case matches.
Switch with an Initialization Statement
An initialization statement can be declared before the expression.
package main
import "fmt"
func main() {
switch day := 4; day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
default:
fmt.Println("Invalid day")
}
}
Output
Thursday
Explanation:
- day := 4 is initialized inside the switch statement.
- day is then evaluated against each case.
- The matching block executes.
Switch Without an Expression
If no expression is specified, switch behaves as switch true, allowing boolean conditions to be used in each case.
package main
import "fmt"
func main() {
day := 4
switch {
case day == 1:
fmt.Println("Monday")
case day == 4:
fmt.Println("Thursday")
case day > 5:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day")
}
}
Output
Thursday
Explanation:
- switch defaults to switch true.
- Each case contains a boolean condition.
- The first condition that evaluates to true executes.
Multiple Case Values
Multiple values can be grouped into a single case.
package main
import "fmt"
func main() {
day := 6
switch day