Go Switch
The switch statement offers a cleaner way to compare one value against many possibilities than a long chain of else if clauses.
A basic switch
Go's switch evaluates an expression once and compares it against each case in order. Unlike C, Java, or JavaScript, Go does not fall through to the next case by default — once a matching case runs, the switch ends automatically. This removes the need for a break statement after every case.
Switch on a value
package main
import "fmt"
func main() {
day := "Wed"
switch day {
case "Sat", "Sun":
fmt.Println("Weekend")
case "Mon", "Tue", "Wed", "Thu", "Fri":
fmt.Println("Weekday")
default:
fmt.Println("Unknown day")
}
}Switch with no condition
When a switch is written without an expression, it behaves like a tidy alternative to if / else if. Each case is a boolean expression, and the first one that evaluates to true wins. This form reads well when the branches test unrelated conditions rather than the same variable.
Expressionless switch
package main
import "fmt"
func main() {
score := 84
switch {
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B")
case score >= 70:
fmt.Println("C")
default:
fmt.Println("F")
}
}The fallthrough keyword
Because Go cases do not fall through automatically, the language provides an explicit fallthrough keyword for the rare occasions you want the next case to run regardless of whether its condition matches. fallthrough must be the last statement in a case block, and it always transfers control to the very next case, never skipping ahead.
Explicit fallthrough
package main
import "fmt"
func main() {
level := 2
switch level {
case 1:
fmt.Println("Basic access granted")
fallthrough
case 2:
fmt.Println("Standard access granted")
fallthrough
case 3:
fmt.Println("Admin access granted")
default:
fmt.Println("No access")
}
}Switching on a type
A special form called a type switch inspects the dynamic type stored in an interface value. It is written as switch v := x.(type), and each case names a concrete type instead of a value.
- switch on a value compares an expression against a fixed set of options.
- switch with no condition acts like a chain of if / else if tests.
- type switch (switch v := x.(type)) branches based on a value's underlying type.
- Cases can list several values separated by commas to share one block of code.
- default is optional and can appear anywhere in the case list, though convention places it last.
Exercise: Go Switch
Does a Go switch case fall through to the next case by default?