Go by Example

Switch

Switch statements match values, conditions, and interface values without implicit fall-through.

A switch chooses the first matching case and exits after that case. Go does not fall through automatically.

An init statement can prepare the value being checked. A case can list several matching values:

package main
 
import "fmt"
 
func main() {
    switch day := "Saturday"; day {
    case "Saturday", "Sunday":
        fmt.Println("weekend")
    default:
        fmt.Println("weekday")
    }
 
    n := 42
    switch {
    case n < 0:
        fmt.Println("negative")
    case n == 0:
        fmt.Println("zero")
    default:
        fmt.Println("positive")
    }
}

A type switch checks the concrete type stored in an interface value:

func describe(value any) {
    switch v := value.(type) {
    case string:
        fmt.Println("text:", v)
    case int:
        fmt.Println("number:", v)
    default:
        fmt.Printf("other: %T\n", v)
    }
}

In production

Use a type switch when behavior depends on an interface value's concrete type. Prefer methods on a small interface when callers should not need to know which concrete types they receive.

Enjoyed this? Get more software craft delivered to your inbox.