In Go, switch
statements are case-oriented, and a case
block will execute if the specified condition is matched. The keyword fallthrough
allows us to execute the next case
block without checking its condition. In other words, we can merge two case
blocks by using the keyword fallthrough
.
case x:
// add content of case block here
fallthrough
case y: //the next case block
In Go,
fallthrough
is not the default behavior. We have to mention it explicitly.
package mainimport "fmt"func main() {num := 0switch num {case 0:fmt.Println("Case: 0")fallthrough // Case 1 will also executecase 1:fmt.Println("Case: 1")case 2:fmt.Println("Case: 2")default:fmt.Println("default")}}
fallthrough
transfers the control to the first line of the case 1
block, so that this block also gets executed.The keyword
fallthrough
must be the last non-empty line of acase
block. Otherwise, it will not work.
Free Resources