0
0
GoConceptBeginner · 3 min read

What is fallthrough in Go switch: Explanation and Example

In Go, fallthrough is a keyword used inside a switch case to continue execution to the next case regardless of its condition. It allows the program to run the code in the following case even if its condition does not match.
⚙️

How It Works

Imagine a switch statement as a set of doors, each representing a case. Normally, when you open one door (match a case), you enter that room and stop. But with fallthrough, it's like leaving the first door open and walking straight into the next room without checking if you should.

In Go, after a case block runs, the switch normally stops. Using fallthrough tells Go to ignore the usual stop and continue running the next case's code. This happens even if the next case's condition is false.

This is different from some other languages where cases automatically continue. In Go, you must explicitly write fallthrough to get this behavior.

💻

Example

This example shows how fallthrough makes the switch run the next case's code even if it doesn't match.

go
package main

import "fmt"

func main() {
    day := 2
    switch day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
        fallthrough
    case 3:
        fmt.Println("Wednesday")
    default:
        fmt.Println("Another day")
    }
}
Output
Tuesday Wednesday
🎯

When to Use

Use fallthrough when you want to run code in multiple cases in a row, like stacking actions together. For example, if several cases share some steps, you can avoid repeating code by falling through.

However, use it carefully because it can make code harder to read if overused. It's best for simple cases where you want to add extra behavior after a match.

Real-world uses include handling grouped conditions or adding default steps after specific cases.

Key Points

  • fallthrough forces execution to continue to the next case.
  • It ignores the next case's condition.
  • Must be the last statement in a case block.
  • Helps avoid code duplication for shared actions.
  • Use sparingly to keep code clear.

Key Takeaways

The fallthrough keyword makes Go switch continue to the next case regardless of its condition.
Without fallthrough, Go switch stops after the first matching case runs.
Use fallthrough to share code between cases but avoid overusing it to keep code readable.
fallthrough must be the last statement in a case block.
It is different from other languages where cases automatically fall through.