Go core · 3 MIN READ

switch does not fall through

Write a Go switch without reaching for break.

In C, Java and JavaScript a case runs on into the next one unless you write break. Go inverted that: a case ends at the next case, and fallthrough is the keyword you write on the rare occasion you want the old behaviour. You do not need break just to end a case, though an explicit break can leave a switch early.

Two more differences worth having: a case can list several values separated by commas, and a switch with no expression is a tidy way to write a chain of conditions.

SEE THE IDEA

The first matching case finishes the switch

  1. 01

    Evaluate

    go
    switch {

    Conditions are checked in order

  2. 02

    Choose

    go
    case ready:

    Run the first matching case

  3. 03

    Finish

    go
    default:

    No implicit fallthrough

An expressionless switch is a sequence of conditions, not a loop.

In practice

Put more specific conditions before broader ones. Several values can share one case, so avoid repeating an identical body. A break can explicitly leave a switch early, but no break is needed merely to stop at the end of a case.

Watch out

fallthrough runs the next case body without testing its condition. Use it only when that behavior is intentional.

Official reference ↗

Work through the exercise

go
package main

// Classify returns "small" for n under 10, "medium" under 100,
// and "large" otherwise. Write it with a switch that has no
// expression after the keyword.
func Classify(n int) string {
	return ""
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.