Skip to content
AgileLogics
5 min read

Switch

Prerequisites: Conditionals

Syntax

switch value {
case 1:
    // ...
case 2, 3:          // several values in one case
    // ...
default:
    // none of the above
}

Unlike C, Java, or JavaScript, a Go switch does not fall through — only the matching case runs, so there's no break to forget. If you really do want to continue into the next case, write fallthrough explicitly (it's rarely needed).

A switch with no value after it (a tagless switch) checks each case as a boolean condition — a tidy replacement for a long if/else if chain.

Example

package main

import "fmt"

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

    score := 82
    switch {
    case score >= 90:
        fmt.Println("Grade A")
    case score >= 80:
        fmt.Println("Grade B")
    case score >= 70:
        fmt.Println("Grade C")
    default:
        fmt.Println("Keep practising")
    }

    switch n := 2; n {
    case 2:
        fmt.Println("two")
        fallthrough
    case 3:
        fmt.Println("reached via fallthrough")
    case 4:
        fmt.Println("not printed")
    }
}

Expected output

Weekend
Grade B
two
reached via fallthrough

Cases are checked top to bottom and the first match wins — which is why 82 prints Grade B and not Grade C.

Common mistakes

  • Adding break at the end of every case out of habit — it's harmless but unnecessary.
  • Expecting fallthrough to check the next case's condition. It doesn't: it runs the next case's body unconditionally.
  • Listing the same constant value in two cases — a compile error (duplicate case).

Practice

Given month := 7, use a switch to print the season in the northern hemisphere: Winter (12, 1, 2), Spring (3–5), Summer (6–8), or Autumn (9–11).

Show solution
package main

import "fmt"

func main() {
    month := 7

    switch month {
    case 12, 1, 2:
        fmt.Println("Winter")
    case 3, 4, 5:
        fmt.Println("Spring")
    case 6, 7, 8:
        fmt.Println("Summer")
    case 9, 10, 11:
        fmt.Println("Autumn")
    default:
        fmt.Println("Invalid month")
    }
}