How to Use fallthrough in Go Switch Statements

Use `fallthrough` in a Go switch statement to explicitly execute the code block of the next case immediately after the current one finishes, bypassing the default behavior of stopping after a case matches.

Use fallthrough in a Go switch statement to explicitly execute the code block of the next case immediately after the current one finishes, bypassing the default behavior of stopping after a case matches. This is useful when you need to chain logic across multiple cases without duplicating code, but it should be used sparingly to avoid making control flow hard to follow.

Here is a practical example where fallthrough accumulates a result based on a severity level:

package main

import "fmt"

func main() {
    level := 2
    var message string

    switch level {
    case 1:
        message = "Low priority: "
        fallthrough
    case 2:
        message += "Medium priority: "
        fallthrough
    case 3:
        message += "High priority: "
    default:
        message = "Unknown level"
    }

    fmt.Println(message) 
    // Output: Medium priority: High priority:
}

In this snippet, when level is 2, the switch executes the case 2 block, hits fallthrough, and immediately runs the case 3 block. Without fallthrough, it would stop after case 2.

Be careful not to confuse fallthrough with the behavior of C or JavaScript switch statements. In Go, cases do not fall through by default; you must explicitly write fallthrough to continue to the next case. If you omit it, the switch exits after the matched case completes.

Another common pattern is handling multiple input values that share a common cleanup step:

switch status {
case "pending", "processing":
    fmt.Println("Job is active")
    fallthrough
case "completed":
    fmt.Println("Sending notification")
    // Shared logic for active and completed jobs
}

Here, if the status is "pending" or "processing", it prints "Job is active" and then falls through to print "Sending notification". If the status is "completed", it skips the first print and goes straight to the notification.

Remember that fallthrough only moves to the immediately following case block. It does not skip cases or jump to a specific label. If you need complex branching logic, consider using if-else chains or helper functions instead, as excessive use of fallthrough can make code harder to read and maintain. Always ensure the logic remains clear to anyone reviewing the code later.