Beginner Fundamentals

Switch

A switch compares a value against several cases. It is often cleaner than a long chain of if/else.

Basic switch

Go does not fall through by default, so you do not need break at the end of each case.

day := "Mon"
switch day {
case "Sat":
    fmt.Println("Weekend")
case "Sun":
    fmt.Println("Weekend")
default:
    fmt.Println("Weekday")
}

Multiple values in one case

List several values separated by commas.

switch day {
case "Sat", "Sun":
    fmt.Println("Weekend")
default:
    fmt.Println("Weekday")
}

Switch with no expression

Without a value, each case is a boolean condition. This replaces a long if/else chain.

score := 75
switch {
case score >= 90:
    fmt.Println("A")
case score >= 80:
    fmt.Println("B")
default:
    fmt.Println("C or lower")
}

fallthrough

If you truly want to continue to the next case, use fallthrough explicitly.

switch 1 {
case 1:
    fmt.Println("one")
    fallthrough
case 2:
    fmt.Println("two")
}