Go Switch: Conditional Execution with Multiple Cases
Learn how to use the switch statement in Go for efficient conditional branching. Understand the syntax, different case scenarios, and best practices for writing clean and effective switch statements.
The switch statement in Go provides a concise way to handle multiple conditional branches based on the value of an expression. It's a cleaner alternative to nested if-else statements for certain scenarios.
Basic Switch Syntax
The switch statement evaluates the expression once and compares it to each case value. If a match is found, the corresponding code block is executed. The default case is optional and runs if no other cases match.
Syntax
switch expression {
case value1:
// Code to execute if expression equals value1
case value2:
// Code to execute if expression equals value2
case value3:
// Code to execute if expression equals value3
default:
// Code to execute if no cases match
}
Example:
Syntax
package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Weekday")
}
}
Output
Wednesday
Multiple Cases in a Single Case
You can group multiple values in a single case using commas:
Syntax
switch day {
case 1, 2, 3:
fmt.Println("Weekday")
case 6, 7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day")
}
Output
Weekday
Conditional Expressions in Cases
You can use comparison operators within case statements:
Syntax
x := 10
y := 5
switch {
case x > y:
fmt.Println("x is greater than y")
case x < y:
fmt.Println("x is less than y")
default:
fmt.Println("x is equal to y")
}
Output
x is greater than y
Fallthrough Keyword
The fallthrough keyword allows execution to continue to the next case, even if the current case matches. Use it with caution, as it can often lead to unexpected behavior.
Syntax
switch num := 2; num {
case 1:
fmt.Println("One")
fallthrough
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}
Output
Two
Other
Type Switches
Go also supports type switches to determine the type of an interface value:
Syntax
package main
import "fmt"
func do(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("Two times %v is %v\n", v, v*2)
case string:
fmt.Printf("Length of %s is %d\n", v, len(v))
default:
fmt.Printf("I don't know about type %T\n", v)
}
}
func main() {
do(21)
do("hello")
do(true)
}
Output
Two times 21 is 42
Length of hello is 5
I don't know about type bool
By effectively using switch statements, you can write more concise and readable conditional logic in your Go code.