Can a Go `switch` statement's cases overlap in a tagless switch (e.g., `case x > 10` and `case x > 5`)? Explain how Go evaluates and executes such cases.
Go & Rust interview question for Advanced practice.
Answer
Yes, cases in a tagless switch statement can overlap logically. In a tagless switch (equivalent to switch true), Go evaluates the case expressions from top to bottom. The first case that evaluates to true is executed, and the switch statement terminates immediately (unless a fallthrough is used). This means the order of the cases is critically important. If cases overlap, only the first matching one will ever be triggered. Example: go package main import "fmt" func main() { x := 15 switch { case x 5: fmt.Println("x is greater than 5") case x 10: // This case is unreachable if x 10 fmt.Println("x is greater than 10") } // Output: x is greater than 5 } In the example, even though x 10 is also true, the switch executes the first true case it finds, which is x 5, and then exits. To fix this kind of logic, you must order cases from most specific to least specific.
Explanation
The behavior of a tagless switch, where the first true case is chosen, makes it a powerful tool for implementing priority-based logic cleanly.