Fallthrough statements

August 22, 2024

Fallthrough statements

A “fallthrough” statement transfers control to the first statement of the next case clause in an expression “switch” statement. It may be used only as the final non-empty statement in such a clause.

FallthroughStmt = "fallthrough" .

Well that’s pretty straight forward.

for x := range 10 {
	switch {
	case x%2 == 0:
		fmt.Print("X")
		fallthrough
	case x%3 == 0:
		fmt.Print("x")
		fallthrough
	case x%5 == 0:
		fmt.Print("O")
	}
	fmt.Println()
}

In this ridiculous example, we get the following output:

XxO

XxO
xO
XxO
O
XxO

XxO
xO

The important thing to notice is that every line that contains (non-empty) output, the final case (which outputs O) is triggered.

The fallthrough unconditionally falls through to the next case. In other words, it doesn’t simply continue evaluating the options. If you want that, switch isn’t what you need—you need just a list of if conditions instead.

Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Terminating switch statements

Terminating statements … A “switch” statement in which: there are no “break” statements referring to the “switch” statement, there is a default case, and the statement lists in each case, including the default, end in a terminating statement, or a possibly labeled “fallthrough” statement. This should make good sense, but let’s look at an example, and a counter-example, to illustrate. func greet(args ...string) error { switch len(args) { case 0: return errors.


Continue statements

Let’s continue… haha See what I did there? Bleh, okay. Continue statements A “continue” statement begins the next iteration of the innermost enclosing “for” loop by advancing control to the end of the loop block. The “for” loop must be within the same function. ContinueStmt = "continue" [ Label ] . There’s not a lot necessary to say here. continue works very much like break. The scoping rules are essentially the same.


Break statements with labels

Break statements … If there is a label, it must be that of an enclosing “for”, “switch”, or “select” statement, and that is the one whose execution terminates. In other words, you can’t break to a label that labels a more deeply nested for, switch or select statement, or to one that’s completely unrelated. But that’s only intuitive, right? OuterLoop: for i = 0; i < n; i++ { for j = 0; j < m; j++ { switch a[i][j] { case nil: state = Error break OuterLoop case item: state = Found break OuterLoop } } } Speaking of labels, did you know that you can have blank labels?

Get daily content like this in your inbox!

Subscribe