Switch
switch picks one branch out of many by comparing a value against a list of cases. Go's version never falls through by accident, accepts several values per case, and can drop the value entirely to become a tidy if-else chain.
Detailed Explanation
You are mapping HTTP status codes to log levels. With if/else if you would write five comparisons against the same variable and repeat that variable five times. A switch names the value once and then lists the interesting cases underneath it. That is the whole reason the statement exists: it turns a repetitive comparison chain into a table you can read down.
No implicit fallthrough. In C and Java, a case body runs into the next one unless you write break. Missing break is one of the oldest bug sources in programming. Go inverts the default: each case ends on its own, and you never write break to terminate a case. If you genuinely want the next body to run, you write fallthrough as the last statement of the case. It is rare, and because it is rare it is obvious when it appears.
Comma-separated cases. case 200, 201, 204: matches any of the three. This covers most of what people used fallthrough for in C, without the hazard.
The tagless switch. Leave out the value after switch and Go behaves as if you had written switch true. Every case is then a boolean expression, evaluated top to bottom, and the first true one wins:
switch {
case score >= 90:
grade = "A"
case score >= 80:
grade = "B"
}
This is the idiomatic way to write a long if-else chain in Go. It lines the conditions up in one column, so the reader can scan the boundaries instead of parsing else if keywords.
Cases are not limited to constants. Unlike Java's classic switch, Go cases can be arbitrary expressions, including function calls. They are evaluated in order until one matches, so a switch is not always the constant-time jump table you might assume. With constant integer or string cases the compiler can and does build a jump table or binary search; with computed cases it is a sequential test.
default and ordering. default runs when nothing matched. It can be written anywhere in the body, but by convention it goes last. Omitting it means "do nothing if nothing matched", which is fine when that is truly what you want and a silent bug when it is not.
Init statement. Like if, a switch can run a statement first: switch day := time.Now().Weekday(); day {. The variable is scoped to the switch.
break means something different here. Inside a switch, break exits the switch. If that switch sits inside a for loop, break does not leave the loop — this surprises nearly everyone once. To leave the loop you label it and write break myLoop. The same applies to a select inside a loop.
What it costs. Nothing measurable in most code. Readability is the real trade: a switch with ten cases that each do five lines of work is worse than ten small functions plus a map lookup. Reach for a map[string]handler when the branches are uniform and data-driven, and a switch when they are genuinely different logic.
Code Examples
package main
import "fmt"
func main() {
// Expression switch. Each case ends by itself; no break needed.
status := 404
switch status {
case 200, 201, 204: // comma-separated: any of these matches
fmt.Println("success")
case 400, 404:
fmt.Println("client error")
default:
fmt.Println("something else")
}
// Tagless switch: no value after `switch`, so every case is a
// boolean test. The first true case wins.
score := 87
switch {
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B") // this one runs
default:
fmt.Println("C")
}
// Init statement, same idea as in an if.
switch day := 6; day {
case 6, 7:
fmt.Println("weekend")
default:
fmt.Println("weekday")
}
}fallthrough runs the NEXT case body unconditionally.
// fallthrough runs the NEXT case body unconditionally.
// It does not re-test that case's expression.
func permissions(role string) []string {
var perms []string
switch role {
case "admin":
perms = append(perms, "delete")
fallthrough // must be the final statement in the case
case "editor":
perms = append(perms, "write")
fallthrough
case "viewer":
perms = append(perms, "read")
}
return perms
}
// permissions("admin") -> [delete write read]
// permissions("editor") -> [write read]
// permissions("guest") -> [] (nil slice, no case matched)`break` inside a switch leaves the switch, not the loop.
// `break` inside a switch leaves the switch, not the loop.
// Label the loop when you need to leave both.
func scanCodes(codes []int) int {
found := -1
scan:
for i, c := range codes {
switch {
case c >= 500:
found = i
break scan // leaves the for loop, not only the switch
case c == 0:
continue scan // next iteration of the labelled loop
}
}
return found
}Common Gotchas
`break` inside a switch does not exit the enclosing loop
it exits the switch, and the loop continues to its next iteration. Label the loop and write `break myLabel` when you mean the loop.
`fallthrough` skips the next case's condition
it transfers control into the next body no matter what that case tests for. It is also illegal in the last case and illegal in a type switch.
Duplicate constant cases are a compile error
`case 1: ... case 1:` will not build when the cases are constants. Duplicated non-constant expressions compile fine and the second one is simply unreachable.
Cases are evaluated in order
a switch over computed expressions is a sequential chain of tests, not a jump table. Put the common case first when the branch count is large and the expressions are not constants.