Explain fallthrough
Explain fallthrough
In an expression switch, fallthrough explicitly transfers control to the statements of the next case, without testing that case condition. It must be the final non-empty statement of a case clause and cannot appear in the final clause. Prefer ordinary cases unless this special behavior is intentional.
package main
import "fmt"
func main() { level := 1 switch level { case 1: fmt.Println("first") fallthrough case 2: fmt.Println("second") case 3: fmt.Println("third") }}Although level is not 2, the second body runs. The third body does not run because the second has no fallthrough. This is different from matching multiple cases. Fallthrough does not work in a type switch (a later lesson topic).
Prefer grouped cases for shared behavior
package main
import "fmt"
func main() { role := "editor" switch role { case "editor", "admin": fmt.Println("can edit") default: fmt.Println("read only") }}If two inputs need the same action, grouping is clearer and avoids accidental execution of unrelated code. Fallthrough cannot be placed inside a nested if in a case body: it must be at the top level and last in that clause.
Try it locally
Use switch on stage := 2. In case 2 print prepare then fall through to case 3 to print finish. Add a case 1 printing start without fallthrough. Expected lines: prepare and finish.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Branching 05: Explain fallthrough
Check the lesson objective before moving on.
Does fallthrough evaluate the next case condition?
Which is valid placement of fallthrough?