What is the fallthrough keyword in Go?
Overview
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.
Syntax
case x:
// add content of case block here
fallthrough
case y: //the next case block
In Go,
fallthroughis not the default behavior. We have to mention it explicitly.
Demo code
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")}}
Explanation
- Line 9: The keyword
fallthroughtransfers the control to the first line of thecase 1block, so that this block also gets executed.
The keyword
fallthroughmust be the last non-empty line of acaseblock. Otherwise, it will not work.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved