Switch
Switch statements match values, conditions, and interface values without implicit fall-through.
A switch chooses the first matching case and exits after that case. Go does not fall through automatically.
A short setup statement can prepare the value before the switch checks it. A case can list several values that should choose the same branch:
package main
import "fmt"
func main() {
switch day := "Saturday"; day {
case "Saturday", "Sunday":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}
n := 42
switch {
case n < 0:
fmt.Println("negative")
case n == 0:
fmt.Println("zero")
default:
fmt.Println("positive")
}
}A type switch checks the actual type stored in an interface value. An interface defines the methods a value must have to be used in a particular way:
func describe(value any) {
switch v := value.(type) {
case string:
fmt.Println("text:", v)
case int:
fmt.Println("number:", v)
default:
fmt.Printf("other: %T\n", v)
}
}In production
Use a type switch when behavior must change based on the actual type inside an interface. Otherwise, let the interface's methods decide what happens so callers do not need to know the specific type.
Enjoyed this? Get more software craft delivered to your inbox.