GGistDev

switch in Go

switch selects a branch based on a value or condition. No implicit fallthrough.

Basic

Cases compare with == semantics and can list multiple matching values separated by commas.

switch day {
case "Mon", "Tue":
    // multiple matching values
case "Sat", "Sun":
    // weekend
default:
    // other
}

With short initialization

Declare a temporary scoped to the switch. An empty tag (switch { ... }) creates a tagless switch.

switch h := hour(); {
case h < 12:
    // morning
case h < 18:
    // afternoon
default:
    // evening
}

Tagless switch (conditions)

Use when each case is a boolean condition; evaluated top to bottom until the first true case.

switch {
case x < 0:
    // ...
case x == 0:
    // ...
default:
    // ...
}

Type switch

Inspect dynamic types behind an interface. Bind the asserted value with v := x.(type) syntax in cases.

func kind(v any) string {
    switch v.(type) {
    case int:
        return "int"
    case string:
        return "string"
    default:
        return "unknown"
    }
}

fallthrough (rare)

Fallthrough executes the next case body unconditionally—use sparingly and comment intent.

switch n := 2; n {
case 1:
    // ...
case 2:
    // do case 2 then also run next case body
    fallthrough
case 3:
    // ...
}

Tips

  • No implicit fallthrough; each case ends after its body
  • Cases compare with == semantics; use tagless form for ranges/conditions
  • Keep cases small and clear; extract logic to functions for readability
  • Prefer type switches for interface values when behavior depends on concrete type

Summary

  • Use tagless switches for conditions, type switches for dynamic types
  • Prefer readability over clever fallthrough chains