Switch
Switch statements express conditionals across many branches. Go's switch is more powerful than in many other languages, with flexible matching and automatic break behavior.
Key Points
- Cases break automatically - no
breakstatement needed - Use
fallthroughto explicitly continue to the next case - Multiple expressions can be tested in a single case
- Switch without an expression acts like if/else chain
- Type switches let you determine the concrete type of an interface value
defaultcase is optional and can appear anywhere
Basic Switch
The most basic switch compares a value against multiple cases:
package main
import (
"fmt"
"time"
)
func main() {
i := 2
fmt.Print("Write ", i, " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}Write 2 as twoMultiple Expressions in Case
You can use multiple expressions in a case statement, separated by commas:
package main
import (
"fmt"
"time"
)
func main() {
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
}It's a weekdaySwitch Without Expression
A switch without an expression is an alternate way to express if/else logic:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
}It's after noonType Switch
A type switch compares types instead of values, useful for working with interfaces:
package main
import "fmt"
func whatAmI(i interface{}) {
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool")
case int:
fmt.Println("I'm an int")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
func main() {
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}I'm a bool
I'm an int
Don't know type stringSwitch Patterns
| Pattern | Example | Description |
|---|---|---|
switch val { case x: } | switch i { case 1: } | Basic switch with value comparison |
case x, y: | case 1, 2, 3: | Multiple values in one case |
switch { case cond: } | switch { case x > 5: } | Switch without expression (if/else alternative) |
switch v := x.(type) | switch t := i.(type) | Type switch for interface values |
default: | default: fmt.Println("other") | Runs if no case matches |
Switch vs Other Languages
| Feature | Go Behavior | Notes |
|---|---|---|
| Automatic break | Cases break automatically | No fall-through by default |
`fallthrough` | Explicit keyword to fall through | Rarely needed, use with caution |
| Expression types | Can switch on any comparable type | Not limited to integers |
default position | Can appear anywhere | Doesn't need to be last |