Richard Bucker

GOLANG switch fallthrough behavior

Posted at — Jun 27, 2013

GO implements the switch instruction as a hodgepodge of different languages. For example:

switch test_variable {case ‘A’:   …default:  …}
and then there is:

switch  {case test_variable == ‘A’:   …default:  …}
Both of the above are identical. I suppose that under the hood there may be an optimization or two.

When comparing the execution to the C model. When GO reaches the end of the case or default block the code continues execution with the command immediately following the end of the switch. C, on the other hand, requires a “break” command in order to get the same behavior.

A nearly opposite is also true. If one omits the “break” statement then the C executable will continue to the next case or break statement until either a break, continue or the end of the switch is reached. By comparison the GO switch statement implements a “fallthrough” statement which tells the GO program to continue to the next case or default statement. One strange side effect is that if there is a test with the next case statement it is ignored.

Here is an interesting example.