Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang

What is the fallthrough keyword in Go?

Hunain Tahir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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, fallthrough is not the default behavior. We have to mention it explicitly.

Demo code

package main
import "fmt"

func main() {
  num := 0
  switch num { 
    case 0:
      fmt.Println("Case: 0")
      fallthrough   // Case 1 will also execute
    case 1:
      fmt.Println("Case: 1")
    case 2:
      fmt.Println("Case: 2")
    default:
      fmt.Println("default")
  }
}
The keyword fallthrough in a switch statement

Explanation

  • Line 9: The keyword 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 a case block. Otherwise, it will not work.

RELATED TAGS

golang

CONTRIBUTOR

Hunain Tahir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring