Go Gopher How to Go

Switch statements express conditionals across many branches. Go's switch is more powerful than in many other languages, with flexible matching and automatic break behavior.

💡 Key Points

  • Cases break automatically - no break statement needed
  • Use fallthrough to explicitly continue to the next case
  • Multiple expressions can be tested in a single case
  • Switch without an expression acts like if/else chain
  • Type switches let you determine the concrete type of an interface value
  • default case is optional and can appear anywhere

Basic Switch

The most basic switch compares a value against multiple cases:

package main

import (
    "fmt"
    "time"
)

func main() {
    i := 2
    fmt.Print("Write ", i, " as ")
    switch i {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    case 3:
        fmt.Println("three")
    }
}
Output:
Write 2 as two

Multiple Expressions in Case

You can use multiple expressions in a case statement, separated by commas:

package main

import (
    "fmt"
    "time"
)

func main() {
    switch time.Now().Weekday() {
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend")
    default:
        fmt.Println("It's a weekday")
    }
}
Output:
It's a weekday

Switch Without Expression

A switch without an expression is an alternate way to express if/else logic:

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("It's before noon")
    default:
        fmt.Println("It's after noon")
    }
}
Output:
It's after noon

Type Switch

A type switch compares types instead of values, useful for working with interfaces:

package main

import "fmt"

func whatAmI(i interface{}) {
    switch t := i.(type) {
    case bool:
        fmt.Println("I'm a bool")
    case int:
        fmt.Println("I'm an int")
    default:
        fmt.Printf("Don't know type %T\n", t)
    }
}

func main() {
    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")
}
Output:
I'm a bool
I'm an int
Don't know type string

Switch Patterns

PatternExampleDescription
switch val { case x: }switch i { case 1: }Basic switch with value comparison
case x, y:case 1, 2, 3:Multiple values in one case
switch { case cond: }switch { case x > 5: }Switch without expression (if/else alternative)
switch v := x.(type)switch t := i.(type)Type switch for interface values
default:default: fmt.Println("other")Runs if no case matches

Switch vs Other Languages

FeatureGo BehaviorNotes
Automatic breakCases break automaticallyNo fall-through by default
`fallthrough`Explicit keyword to fall throughRarely needed, use with caution
Expression typesCan switch on any comparable typeNot limited to integers
default positionCan appear anywhereDoesn't need to be last