![]() |
VOOZH | about |
In Go, a switch statement is a multiway branch statement that efficiently directs execution based on the value (or type) of an expression. There are two main types of switch statements in Go:
Example
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")
}
}
switch optstatement; optexpression {
case expression1:
// Code block
case expression2: # Expression Switch
// Code block
default:
// Code block
}
switch var := interfaceValue.(type) {
case type1:
// Code block
case type2: # Type Switch
// Code block
default:
// Code block
}Table of Content
The Expression Switch evaluates an expression and branches to a case based on the value of that expression. If no expression is provided, switch defaults to true.
switch optstatement; optexpression {
case expression1:
// Code block
case expression2:
// Code block
default:
// Code block
}
true).Here, we introduce an optional statement that declares a variable day. The switch statement then evaluates day against various cases.
Thursday
If no expression is specified, the switch statement assumes the expression is true. This allows us to use boolean conditions in the case statements.
Thursday
A Type Switch is used to branch on the type of an interface value, rather than its value. This is particularly useful when dealing with variables of unknown types.
switch var := interfaceValue.(type) {
case type1:
// Code block
case type2:
// Code block
default:
// Code block
}
Example
In this example, we use the same day variable but wrapped in an interface{} to demonstrate the type switch.
Thursday