Go Switch
A switch statement compares a value against a list of cases and runs the first one that matches. It is a cleaner alternative to long if … else if chains. Go's switch is friendlier than C's: cases do not fall through to the next one, so you never need break.
Basic switch
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("Some other day")
}
}Wednesday
The default case runs when no other case matches. It is optional and can be placed anywhere, though by convention it goes last.
Several values in one case
Separate values with commas to share one case body.
package main
import "fmt"
func kind(ch string) string {
switch ch {
case "a", "e", "i", "o", "u":
return "vowel"
case " ":
return "space"
default:
return "consonant"
}
}
func main() {
for _, ch := range []string{"g", "o", " ", "u"} {
fmt.Printf("%q is a %s\n", ch, kind(ch))
}
}"g" is a consonant
"o" is a vowel
" " is a space
"u" is a vowel
Switch without a value
If you leave out the value after switch, each case is a boolean expression. This is the idiomatic way to write a long if-else chain.
package main
import "fmt"
func bmiCategory(bmi float64) string {
switch {
case bmi < 18.5:
return "underweight"
case bmi < 25:
return "normal"
case bmi < 30:
return "overweight"
default:
return "obese"
}
}
func main() {
for _, v := range []float64{17.2, 22.8, 27.1, 33.0} {
fmt.Println(v, bmiCategory(v))
}
}17.2 underweight
22.8 normal
27.1 overweight
33 obese
Switch with an init statement
Like if, a switch can start with a short statement whose variables are scoped to the switch.
package main
import (
"fmt"
"strings"
)
func main() {
switch ext := strings.ToLower(".PNG"); ext {
case ".jpg", ".png", ".gif":
fmt.Println(ext, "is an image")
case ".mp3", ".wav":
fmt.Println(ext, "is audio")
default:
fmt.Println(ext, "is unknown")
}
}.png is an image
fallthrough
If you really want execution to continue into the next case body, write fallthrough as the last statement of a case. It skips the next case's condition entirely — so use it rarely and deliberately.
package main
import "fmt"
func main() {
level := 2
fmt.Println("Unlocked:")
switch level {
case 3:
fmt.Println("- expert tools")
fallthrough
case 2:
fmt.Println("- advanced tools")
fallthrough
case 1:
fmt.Println("- basic tools")
}
}Unlocked:
- advanced tools
- basic tools
break inside switch
break inside a switch leaves the switch — not a surrounding loop. To break out of a loop from inside a switch, give the loop a label: outer: for ... { switch { case ...: break outer } }.
| Feature | Go | C / Java |
|---|---|---|
| Automatic fall-through | no | yes |
Need break after each case |
no | yes |
| Multiple values per case | case 1, 2, 3: |
stacked cases |
| Case expressions | any comparable value or boolean expression | constants only |
Tip: A
switchcan also branch on the type of an interface value (switch v := x.(type)). That is covered in the Type Assertions chapter.
Test yourself
What happens after a matching case body finishes in Go?
- The next case runs too
- The switch ends
- The default case runs
- The switch starts again
How do you match "sat" or "sun" in one case?
case "sat" || "sun":case "sat", "sun":case "sat": case "sun":case ["sat", "sun"]:
What does switch { case x > 10: ... } (no value after switch) do?
- Compile error
- Compares each case to
true - Compares each case to
0 - Runs every case