Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 147 ยท Operators and Control Flow

switch

Learn Go's switch statement - cases without break, multiple values per case, tagless switch for ranges, init statements, fallthrough, break inside loops and a first look at type switches.

When you need to choose between many alternatives, a long if/else if chain gets noisy. Go's switch is the tidier tool, and it is more flexible than the switch in C or Java: cases do not fall through by default, a case can list several values, the cases can be arbitrary expressions, and a switch without a tag turns into a clean multi-way if.

This lesson covers the expression switch in all its forms, the rarely needed fallthrough keyword, how break behaves inside a switch that sits in a loop, and a short preview of the type switch, which gets its own treatment in Type Assertions and Type Switches.

The expression switch

A switch evaluates its tag expression once, then compares it with each case from top to bottom and runs the first one that matches. When that block finishes, the whole switch is over. No break is needed.

Go A basic switch with default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Things to notice:

  • A case can list several values separated by commas: case "Saturday", "Sunday":.
  • default runs when nothing else matches. It is optional, and it may appear anywhere in the list; the position does not change when it runs (it is always the last resort).
  • The cases do not have to be constants. They can be variables or function calls, and Go evaluates them top to bottom, left to right, stopping at the first match.
  • Duplicate constant cases are a compile error, which catches copy-and-paste mistakes:
Go Duplicate cases (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler rejects the second 404 and points back to the first one:

TEXT
./main.go:12:7: duplicate case 404 (constant of type int) in expression switch
	./main.go:10:7: previous case

The tagless switch

If you leave out the tag, Go uses true as the tag, and each case is a boolean expression. The first case that evaluates to true runs. This is the neat way to write a chain of range checks, and it is often preferred over if/else if when the chain is long.

Go A switch with no tag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because only the first match runs, the order matters: bmi < 25 is only reached when bmi < 18.5 was false, so there is no need to write bmi >= 18.5 && bmi < 25.

An init statement in switch

Like if, a switch can start with a short statement. It is useful for computing a value that you only need for the switch.

Go switch with an init statement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The variable cmd exists only inside the switch, including the default case. You can combine an init statement with the tagless form too: switch x := f(); { case x < 0: ... } (note the semicolon after the init statement).

fallthrough

Sometimes you do want the next case's body to run as well. The fallthrough statement, which must be the last statement of a case, transfers control into the next case body without testing its condition.

Go fallthrough runs the next body unconditionally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Level 3 runs all three bodies, level 2 runs two, and level 1 runs one. Note that fallthrough ignores the next case's expression entirely. It is rare in real Go code; if you reach for it often, a list of values in one case or an if chain is usually clearer. You cannot use fallthrough in the last case, or in a type switch.

break inside a switch

break leaves the innermost switch, for or select. That is handy for leaving a case early, but it surprises people who put a switch inside a loop and expect break to end the loop:

Go break leaves the switch, not the loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first loop keeps going after found 3. The second uses a label (search:) so that break search ends the loop. Labels are explained fully in Labels, break, continue and goto. In a plain for loop, continue does work on the loop, because switch does not catch it.

A first look at type switches

A switch can also branch on the dynamic type of an interface value. The form is switch v := x.(type), and each case names a type. Inside a case that lists exactly one type, v has that type.

Go A type switch on any values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In the bool, float64 case v keeps the type any, because Go cannot pick one type. Interfaces are introduced in Interfaces; come back to this example when you reach them.

Prefer a switch to a long if/else if chain whenever you compare the same value against several options, or when the chain has more than about three branches. For two outcomes, a plain if is clearer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? x := 2; switch x { case 1: fmt.Print("a"); case 2: fmt.Print("b"); case 3: fmt.Print("c") }

    Go cases do not fall through. Only the matching case 2 runs, then the switch ends.
  2. 2. Which line lets one case match both 6 and 7?

    A case lists alternatives separated by commas. With a tagless switch you would write a boolean condition instead.
  3. 3. In a tagless switch { case n < 10: ... case n < 100: ... }, what is compared in each case?

    A missing tag means the tag is true, so each case is a condition. Only the first matching case runs.
  4. 4. A for loop contains switch { case i == 3: break }. What does break do?

    break leaves the innermost switch, for or select. To end the loop you need a label, as in break outer.
  5. 5. What does fallthrough do at the end of a case?

    fallthrough transfers control to the first statement of the next case body unconditionally.

Summary

  • switch compares a tag against case values from top to bottom and runs only the first match; there is no implicit fallthrough and no break needed.
  • A case may list several values: case 1, 2, 3:. default handles everything else.
  • A switch without a tag runs the first case whose boolean condition is true, which replaces long if/else if chains.
  • An init statement (switch x := f(); x {) scopes a helper variable to the switch.
  • fallthrough unconditionally continues into the next case body and is rarely used.
  • break inside a switch leaves only the switch; use a label to leave an enclosing loop.
  • switch v := x.(type) branches on the dynamic type of an interface value.

Next: for Loops