switch statements
- Version
- 1.27
- Review
- Draft
Summary#
An expression switch runs the first case that matches, checking from top to bottom. It stops at the end of that case. Without a switch expression, each case is a condition.
Syntax#
switch value := readValue(); value {
case first, second:
default:
}
switch {
case value > limit:
}
Example#
package main
import "fmt"
func severity(code int) string {
switch { // the first true condition wins
case code >= 500:
return "server error"
case code >= 400:
return "client error"
default:
return "no error"
}
}
func main() {
for _, day := range []string{"sat", "mon", "xyz"} {
switch day {
case "sat", "sun":
fmt.Println(day, "is a weekend day")
case "mon", "tue", "wed", "thu", "fri":
fmt.Println(day, "is a weekday")
default:
fmt.Println(day, "is unknown")
}
}
fmt.Println(severity(503))
fmt.Println(severity(404))
switch plan := "team"; plan {
case "team":
fmt.Println("shared projects")
fallthrough // continue into the next clause
case "solo":
fmt.Println("private projects")
}
}
Expected output#
sat is a weekend day
mon is a weekday
xyz is unknown
server error
client error
shared projects
private projects
Common mistakes#
An empty case does not pass control to the next one. Writing case "sat": on its own line above case "sun": does nothing for "sat". List both values in one case. To enter the next clause without testing it, use fallthrough as the last statement in a non-final case.
Version applicability#
The syntax and example work from Go 1.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0