patterngoCritical
Do Go switch/cases fallthrough or not?
Viewed 0 times
fallthroughswitchnotcases
Problem
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?
Solution
No, Go switch statements do not fall through automatically. If you do want it to fall through, you must explicitly use a
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):
Outputs:
https://play.golang.org/p/va6R8Oj02z
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
Code Snippets
switch 1 {
case 1:
fmt.Println("I will print")
fallthrough
case 0:
fmt.Println("I will also print")
}Context
Stack Overflow Q#40821855, score: 190
Revisions (0)
No revisions yet.