The switch Statement
When a value can lead to one of several different code blocks, a switch statement lets you pick the right one.
If you have used switch in other languages, the Go version will look familiar, with one difference: only the matching case runs. Execution does not carry on into the next case, so you don't write a break at the end of each one.
Single-Case switch Syntax
Go works out the switch expression a single time, then checks the result against each case value. The block under the matching case is the one that runs. You may also add default, which is optional, to supply code for when no case fits.
switch Syntax
switch expression {
case x:
// code block
case y:
// code block
case z:
...
default:
// code block
}
Single-Case switch Example
Here a number stands for a day of the week, and the switch turns it into that day's name. With day set to 4, the result is Thursday.
Example
Output: Go program and captured output
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")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
}
}
The default Keyword
When none of the cases fit, the code under default takes over. In this example, no case covers the value 8, so the default message is printed.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
day := 8
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")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Not a weekday")
}
}
Case Type Must Match
Every case value needs to be of the same type as the switch expression. Mix in a different type and the program will not compile. In this example, a is an int, so the string case "b" causes an error.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
a := 3
switch a {
case 1:
fmt.Println("a is one")
case "b":
fmt.Println("a is b")
}
}