The Flexible Switch

The Flexible Switch in Go: Walk into an emergency department and the first person you meet is a triage nurse with a laminated card on the desk.

The Analogy: The Triage Desk at a Hospital

Walk into an emergency department and the first person you meet is a triage nurse with a laminated card on the desk. The card is a list of rows: chest pain goes to cardiology, a suspected fracture or a sprain goes to orthopedics, no stated complaint goes back to the front desk to fill in the form, and anything not on the card goes to general medicine. The nurse reads the rows in order, and the instant one matches you are sent down that corridor. She does not keep reading the rest of the card "just in case", and she does not need a rule at the bottom of every row saying stop reading now. Matching one row ends the process.

That last detail is the whole difference between Go's switch and the switch you may know from C, C++, Java or JavaScript. In those languages every row needs an explicit break or control spills into the next row, which is why forgetting one is a classic bug and why linters shout about it. In Go, each case ends by itself. You never write break to terminate a case, and if you genuinely want the spill-over behavior you have to ask for it by name with the fallthrough keyword. The safe thing is the default and the dangerous thing is opt-in.

Some rows on the card list several complaints that lead to the same corridor, which is Go's comma-separated case list. And some triage cards do not sort by a complaint code at all: they ask a full question on every row, such as "is the breathing rate above 30" or "is the patient under two years old". Go writes that as a switch with no value after the keyword, where each case is a complete boolean test. It is exactly an if/else-if chain, but formatted as a table so the reader can see all the branches at once instead of chasing indentation down the page.

The desk also handles different kinds of arrivals, not just different complaints: a walk-in patient, an ambulance stretcher, a phone call from a GP. Each kind needs a different form filled in, and the first thing the nurse must establish is which kind is in front of her. That is Go's type switch, the one form of switch that asks what a value is rather than what it equals, and it is how you unpack an any or an interface value into something concrete you can work with. Four jobs, one keyword, and once you can tell the four apart you have most of Go's branching vocabulary.


Syntax or Core Structure

The two most common forms sit side by side here. routeByCode switches on a value, groups two codes into one case, matches the empty string explicitly, and ends with default. routeByScore has no value after switch at all, so each case is its own boolean expression, evaluated top to bottom until one is true.

package main

import "fmt"

func routeByCode(code string) string {
    switch code {
    case "CP":
        return "cardiology"
    case "FX", "SP":
        return "orthopedics"
    case "":
        return "front desk"
    default:
        return "general medicine"
    }
}

func routeByScore(score int) string {
    switch {
    case score >= 9:
        return "resuscitation"
    case score >= 6:
        return "urgent"
    case score >= 3:
        return "standard"
    default:
        return "self care"
    }
}

func main() {
    for _, code := range []string{"CP", "FX", "SP", "", "ZZ"} {
        fmt.Printf("code %-4q -> %s\n", code, routeByCode(code))
    }
    for _, score := range []int{10, 7, 4, 1} {
        fmt.Printf("score %2d  -> %s\n", score, routeByScore(score))
    }
}

Output:

code "CP" -> cardiology
code "FX" -> orthopedics
code "SP" -> orthopedics
code ""   -> front desk
code "ZZ" -> general medicine
score 10  -> resuscitation
score  7  -> urgent
score  4  -> standard
score  1  -> self care

Notice that neither function contains the word break. Each case body ends where the next case keyword begins. routeByScore is an if/else-if chain wearing a different hat: switch { case a: ... case b: ... } compiles to the same thing as if a { ... } else if b { ... }, and Go programmers reach for it the moment a chain grows past two branches because the cases line up in a column and a missing branch is visible at a glance.


Technical Depth: One Keyword, Four Jobs

Every switch in Go is one of four shapes. Learning to name them makes reading unfamiliar code much faster.

FormWritten asWhat each case holds
Expression switchswitch x { ... }A value comparable to x
Expressionless switchswitch { ... }A full boolean expression
With initializerswitch v := f(); v { ... }A value comparable to v
Type switchswitch v := x.(type) { ... }A type name, or nil

switch and switch true are the same statement: when the value is omitted the compiler substitutes true, so each case is compared against true, which is why boolean expressions work there. The initializer form follows the same scoping rule as if: the variable exists for the whole switch including every case body and the default, and nowhere else.

No Implicit Fallthrough

In C, case 1: without a break runs the body of case 2 as well. Go inverts this. The specification says a case body ends with an implicit break, so control leaves the switch as soon as the matched body finishes.

You writeC doesGo does
Two cases, no breakRuns both bodiesRuns only the matched body
break at the end of a caseRequiredRedundant, and vet-clean but noisy
Deliberate spill-overOmit breakWrite fallthrough

fallthrough has three hard rules worth memorizing. It must be the final statement in the case body, it jumps into the next case body without evaluating that case's condition, and it is illegal in a type switch and in the last case of any switch. Because it skips the condition, fallthrough can land you in a branch whose test would have been false, which is exactly why it is rare in real code.

The honest use for fallthrough is accumulating: every tier includes the tiers below it.

func medals(score int) []string {
    var earned []string
    switch {
    case score >= 90:
        earned = append(earned, "gold")
        fallthrough
    case score >= 70:
        earned = append(earned, "silver")
        fallthrough
    case score >= 50:
        earned = append(earned, "bronze")
    case score >= 0:
        earned = append(earned, "participant")
    }
    return earned
}

func main() {
    for _, s := range []int{95, 75, 60, 20} {
        fmt.Printf("%3d -> %v\n", s, medals(s))
    }
}

Output:

 95 -> [gold silver bronze]
 75 -> [silver bronze]
 60 -> [bronze]
 20 -> [participant]

A score of 95 collects all three because each fallthrough enters the next body regardless of its condition. A score of 20 reaches participant only because the bronze case has no fallthrough at the end, so control leaves the switch. Change one fallthrough and the meaning of four other branches changes with it, which is the reason to keep this pattern for the rare case where it really is a ladder.

Case Expressions Are Evaluated in Order

A C switch on small integers often compiles to a jump table, which is why C requires case labels to be compile-time constants. Go allows non-constant cases, so it evaluates the case expressions top to bottom, left to right within a case list, and stops at the first match.

ConsequenceWhat it means for you
Order matters in a boolean switchcase score >= 3 before case score >= 9 makes the second unreachable
Case expressions may call functionsSide effects in a case only happen if earlier cases did not match
Duplicate constant cases are rejectedcase 1: ... case 1: fails to compile
Duplicate non-constant cases are allowedcase a: ... case b: compiles even when a == b; the first wins
default position is irrelevantIt runs only when no case matched, wherever you put it

Convention still puts default last, because readers expect the fallback at the bottom of the table.

What You Can Switch On

An expression switch compares with ==, so the same comparability rules from the previous lesson apply exactly.

Type of valueAllowed in a switch
Numbers, strings, booleans, runesYes
Pointers, channelsYes, compares identity
Structs and arrays of comparable fieldsYes, field by field
InterfacesYes, but panics if the dynamic type is uncomparable
Slices, maps, functionsNo, except case nil

Switching on a string is idiomatic and fast; the compiler optimizes it by length and then by content rather than testing every case in turn, so a fifty-case string switch is not a fifty-comparison loop.

The Type Switch

switch v := x.(type) is the only place the token .(type) is legal, and x must be an interface value. Inside each case, v has a different static type: the concrete type named by that case.

CaseStatic type of v inside it
case int:int
case string:string
case []byte:[]byte
case int, int64:The interface type of x, because two types cannot both apply
case nil:Matches when the interface itself is nil
default:The interface type of x

The two-types-in-one-case rule catches everybody once: the moment you list more than one type, v stops being concrete and you are back to needing an assertion inside the body. If you do not need the value at all, drop the assignment and write switch x.(type). Also note that case nil tests the interface, not the pointer inside it: an interface holding a nil *User is not nil and will match case *User instead.

break, continue and Labels

Inside a switch that sits in a loop, the two keywords behave asymmetrically and the difference bites people who assume symmetry. continue has nothing to do with the switch and goes straight to the next loop iteration. break binds to the nearest enclosing switch, select or loop, and the switch is nearer, so it leaves the switch and the loop carries on. To leave the loop you need a label.

lines := []string{"# header", "", "ok 1", "STOP", "ERR disk full"}

total := 0
scan:
for _, line := range lines {
    switch {
    case line == "" || strings.HasPrefix(line, "#"):
        continue
    case line == "STOP":
        break scan
    default:
        total++
    }
}
fmt.Println("counted:", total)

Output:

counted: 1

Replace break scan with a bare break and the answer becomes counted: 2, because control leaves the switch, the loop advances to ERR disk full, and the default case counts it. The label is not decoration; it is the difference between a parser that stops at the terminator and one that keeps reading past it.


Real World Example: Flattening Decoded JSON

Here is the type switch doing the job it was invented for. You are handed a configuration document and you do not have a struct for it, either because the shape varies by service or because you are writing a tool that must handle any document. json.Unmarshal into an any gives you Go's six generic JSON shapes, and a recursive type switch turns the whole tree into flat dotted keys you can diff, log or grep.

package main

import (
    "encoding/json"
    "fmt"
    "sort"
    "strconv"
)

const doc = `{
  "service": "billing",
  "port": 8080,
  "debug": false,
  "owner": null,
  "limits": {"rps": 250, "burst": 500},
  "regions": ["gb", "de"]
}`

func flatten(prefix string, v any, out map[string]string) {
    switch t := v.(type) {
    case nil:
        out[prefix] = "null"
    case bool:
        out[prefix] = strconv.FormatBool(t)
    case float64:
        out[prefix] = strconv.FormatFloat(t, 'f', -1, 64)
    case string:
        out[prefix] = t
    case []any:
        for i, item := range t {
            flatten(prefix+"["+strconv.Itoa(i)+"]", item, out)
        }
    case map[string]any:
        for k, item := range t {
            key := k
            if prefix != "" {
                key = prefix + "." + k
            }
            flatten(key, item, out)
        }
    default:
        out[prefix] = fmt.Sprintf("unsupported %T", t)
    }
}

The caller sorts the keys before printing, because ranging over a map yields keys in a randomized order and a tool whose output changes between runs is useless for diffing.

func main() {
    var parsed any
    if err := json.Unmarshal([]byte(doc), &parsed); err != nil {
        fmt.Println("bad json:", err)
        return
    }

    out := map[string]string{}
    flatten("", parsed, out)

    keys := make([]string, 0, len(out))
    for k := range out {
        keys = append(keys, k)
    }
    sort.Strings(keys)

    for _, k := range keys {
        fmt.Printf("%-16s = %s\n", k, out[k])
    }
}

Output:

debug            = false
limits.burst     = 500
limits.rps       = 250
owner            = null
port             = 8080
regions[0]       = gb
regions[1]       = de
service          = billing

When json.Unmarshal fills an any, it can only ever produce six shapes: nil, bool, float64, string, []any and map[string]any. The one that surprises everybody is float64. There is no int case to write, because 8080 in JSON arrives as the floating point value 8080, and case int: would silently never match. strconv.FormatFloat(t, 'f', -1, 64) is what prints it as 8080 rather than 8080.000000: the -1 precision asks for the shortest representation that round-trips back to the same float64.

The reason this function is short is that t is a different type in each case. In case []any it is a slice, so range t gives an index and an any. In case map[string]any it is a map, so the same range keyword gives a key and an any. Written with type assertions instead, each branch would need its own t, ok := v.([]any) line and its own ok check, and the compiler would stop helping you the moment one of them was wrong.

The default case earns its keep. If somebody later switches to json.NewDecoder with UseNumber(), every number arrives as a json.Number instead of a float64, and without a default those values would vanish from the output with no complaint at all. Instead the flattened map records unsupported json.Number and the problem is visible in the first test run. A type switch over an open-ended interface should nearly always have a default that reports %T, because the set of types passing through it is not something the compiler can check for you.

Two properties make this safe to put in a build pipeline. It is deterministic: keys are sorted before printing, so the same document always produces byte-identical output and a diff between two config versions means something. And it is total: every value in the tree either becomes a line of output or triggers the default, so nothing is dropped in silence. The one limit to keep in mind is that flatten recurses once per level of nesting, so a hostile document nested ten thousand deep would exhaust the stack. For internal config that is a non-issue; for untrusted input, cap the depth by passing a counter alongside the prefix.


Common Mistakes

  1. Writing break at the end of every case. It does nothing. Go already ends the case, and the extra keyword makes readers wonder what you were guarding against.
  1. Expecting fallthrough by default. Two cases with the same body need a comma-separated case list, not two cases stacked on top of each other.
  1. Using break to leave a loop from inside a switch. It only leaves the switch. Label the loop and break label.
  1. Ordering a boolean switch from narrowest to widest. case n >= 3 above case n >= 9 makes the second branch dead code, and nothing warns you.
  1. Writing case int: for decoded JSON numbers. They are float64. The case compiles, never matches, and the value falls through to default or disappears.
  1. Listing two types in one type-switch case and then using v as concrete. With case int, int64: the variable keeps the interface type and v + 1 will not compile.
  1. Leaving a type switch without a default. Unknown types then vanish silently. Report %T instead.
  1. Assuming case nil catches a nil pointer. An interface holding a nil *User matches case *User, not case nil.
  1. Ranging a map inside a switch and printing as you go. The order is randomized per run. Collect, sort, then print.

Best Practices

  • Reach for an expressionless switch as soon as an if/else-if chain has three or more branches; the cases read as a table.
  • Group equivalent values with a comma-separated case list rather than repeating a body.
  • Order boolean cases from the most restrictive to the least, and read them top to bottom once to confirm none is unreachable.
  • Keep default last even though its position does not matter, and always include one when switching over an interface or over externally supplied data.
  • Treat fallthrough as a signal that the branches form a deliberate ladder, and add a comment saying so.
  • Label the loop whenever a switch inside it needs to terminate the loop, and give the label a meaning such as scan or rows.
  • Prefer switch v := x.(type) over a stack of type assertions, and give v a name only when you use it.
  • Sort before printing anything derived from a map, so the output of a tool is stable enough to diff.

Practice Exercises

  1. Ladder of Medals: Take the medals function and remove one fallthrough. Predict all four outputs before running it, then run it and record which predictions were wrong and why. Rewrite the same logic without fallthrough and decide which version you would rather maintain.
  1. Escape the Loop: Write a loop over at least six log lines with a switch inside that skips comments, stops at a terminator and counts everything else. Run it with a bare break and then with a labeled break, and record both counts.
  1. Extend the Flattener: Add a case json.Number to flatten and decode the same document with json.NewDecoder plus UseNumber(). Confirm the output is identical to the float64 version, then delete the default case, feed it a type it does not handle, and describe exactly what you lose.
  1. Type Switch Router: Write describe(v any) string with cases for nil, bool, string, int, []string, error and a default reporting %T. Call it with at least eight values including a nil error interface and a non-nil error holding a nil pointer, and explain each result in one line.