Fallthrough statements
A “fallthrough” statement transfers control to the first statement of the next case clause in an expression “switch” statement. It may be used only as the final non-empty statement in such a clause.
FallthroughStmt = "fallthrough" .
Well that’s pretty straight forward.
for x := range 10 {
switch {
case x%2 == 0:
fmt.Print("X")
fallthrough
case x%3 == 0:
fmt.Print("x")
fallthrough
case x%5 == 0:
fmt.Print("O")
}
fmt.Println()
}
In this ridiculous example, we get the following output:
XxO
XxO
xO
XxO
O
XxO
XxO
xO
The important thing to notice is that every line that contains (non-empty) output, the final case (which outputs O
) is triggered.
The fallthrough
unconditionally falls through to the next case. In other words, it doesn’t simply continue evaluating the options. If you want that, switch
isn’t what you need—you need just a list of if
conditions instead.
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)