91

What happens when you reach the end of a Go case, does it fall through to the next, or assume that most applications don't want to fall through?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
mcandre
  • 22,868
  • 20
  • 88
  • 147

2 Answers2

146

No, Go switch statements do not fall through automatically. If you do want it to fall through, you must explicitly use a fallthrough statement. From the spec:

In a case or default clause, the last non-empty statement may be a (possibly labeled) "fallthrough" statement to indicate that control should flow from the end of this clause to the first statement of the next clause. Otherwise control flows to the end of the "switch" statement. A "fallthrough" statement may appear as the last statement of all but the last clause of an expression switch.

For example (sorry, I could not for the life of me think of a real example):

switch 1 {
case 1:
    fmt.Println("I will print")
    fallthrough
case 0:
    fmt.Println("I will also print")
}

Outputs:

I will print
I will also print

https://play.golang.org/p/va6R8Oj02z

Grant G
  • 77
  • 7
Sam Whited
  • 6,880
  • 2
  • 31
  • 37
  • 3
    NOTE; The 'fallthrough' must be the last thing in the case; although you can workaround that using [labels](https://github.com/golang/go/wiki/Switch#fall-through) – Edwin O. Mar 07 '18 at 16:14
  • Real example is Duffs device. Though with modern Processors there might not be a speedup. – lalala Jul 04 '21 at 16:45
  • 4
    Keep in mind this doesn't work in a type switch. So `switch y := x.(type)` does not take any fallthrough statements! – Das Jott Feb 24 '22 at 10:38
  • `fallthrough` cannot be used with a type switch. – Zamicol Aug 04 '22 at 20:47
  • 1
    Ouch. Coming from the JavaScript / TypeScript world, this was a huge gotchya for me today. The go linter didn't even warn me about this when I essentially didn't have any implementation for a `case` (because I thought it would fall through automatically!) – fullStackChris Mar 01 '23 at 12:49
18

Break is kept as a default but not fallthrough. If you want to get onto the next case for a match, you should explicitly mention fallthrough.

switch choice {
case "optionone":
    // some instructions 
    fallthrough // control will not come out from this case but will go to next case.
case "optiontwo":
   // some instructions 
default: 
   return 
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Milind Dhoke
  • 549
  • 7
  • 15
  • 9
    Not "for a match": fallthrough will execute the body of the next case, no checking that next case for a match! – PePa May 09 '21 at 03:35