Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Go switch/cases fallthrough or not?

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?

like image 839
mcandre Avatar asked Nov 26 '16 18:11

mcandre


People also ask

Does Golang switch Fallthrough?

fallthrough keyword is used in switch statement in golang. This keyword is used in switch case block. If the fallthrough keyword is present in the case block, then it will transfer control to the next case even though the current case might have matched.

What is Fallthrough in switch case?

Code Inspection: Fallthrough in 'switch' statementReports a switch statement where control can proceed from a branch to the next one. Such "fall-through" often indicates an error, for example, a missing break or return .

Does switch case Go in order?

A switch statement runs the first case equal to the condition expression. The cases are evaluated from top to bottom, stopping when a case succeeds.

How do you use Fallthrough in Golang?

With the help of fallthrough statement, we can use to transfer the program control just after the statement is executed in the switch cases even if the expression does not match. Normally, control will come out of the statement of switch just after the execution of first line after match.


2 Answers

No, Go switch statements do not fall through by default. 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

like image 162
Sam Whited Avatar answered Sep 19 '22 03:09

Sam Whited


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  } 
like image 39
Milind Dhoke Avatar answered Sep 19 '22 03:09

Milind Dhoke