Switch
When you're choosing between more than two or three branches, an if/else if ladder gets noisy. Go's switch is built for exactly that job — and it
fixes the sharpest edge the C-family version has.
Cases break by default
In C, every case falls through into the next one unless you remember to
write break — forget it once and two branches quietly run. Decades of bugs
came from that default. Go flips it: each case breaks automatically.
package main
import "fmt"
func main() {
day := "saturday"
switch day {
case "saturday":
fmt.Println("weekend!")
case "sunday":
fmt.Println("still weekend!")
default:
fmt.Println("back to work")
}
}
Only the matching case runs — no break needed, no accidental
fall-through possible. (A fallthrough keyword exists for the rare day you
truly want the C behavior, but you must ask for it explicitly, which is the
point: the dangerous thing is now the verbose thing.)
Notice default: it runs when nothing else matches, and it doesn't have to
come last — though it usually does.
Several values, one case
When multiple values share a branch, list them in one case, separated by commas — this is Go's answer to C's stacked empty cases:
package main
import "fmt"
func main() {
day := "sunday"
switch day {
case "saturday", "sunday":
fmt.Println("weekend!")
default:
fmt.Println("back to work")
}
}
Switch with no condition
Drop the value after switch entirely and each case becomes a boolean
expression — the first true one wins. It reads like an if/else if chain,
but flatter:
package main
import "fmt"
func main() {
score := 74
switch {
case score >= 90:
fmt.Println("excellent")
case score >= 50:
fmt.Println("pass")
default:
fmt.Println("try again")
}
}
This is idiomatic Go whenever a chain grows past two or three branches: the
conditions line up vertically and every outcome is easy to scan. Like if
and for, a switch can also take an init statement:
switch x := compute(); { ... }.
One sentence on type switches
There's a second kind of switch — switch v := x.(type) — that branches on
what type a value has rather than what value it holds; it belongs to the
interfaces chapter, so file it away for later.
Time to put switch to work: the exercise maps HTTP status codes to their
standard reason phrases — a real function that real servers need, and a
perfect shape for one switch statement.
Practice
1. HTTP Status Text
BeginnerImplement
statusTextso it returns the standard reason phrase for an HTTP status code:func statusText(code int) stringCode Return value 200 "OK"201 "Created"204 "No Content"400 "Bad Request"401 "Unauthorized"403 "Forbidden"404 "Not Found"500 "Internal Server Error"For any other code, return
"Unknown".Use a
switchstatement — this is exactly the shape it was made for. (Strings must match exactly, including capitalization and spaces.)package main import "fmt" // statusText returns the standard reason phrase for an HTTP status code, // or "Unknown" for codes it doesn't recognize. func statusText(code int) string { // TODO: implement return "" } func main() { fmt.Println(statusText(404)) }Sign in to write and run your solution in the browser.
Sign in for hints and the solution.