The Clean Switch

The Clean Switch

The Clean Way

A switch statement checks a value against a list of cases. It's like an if/else chain, but cleaner when you're comparing the same variable multiple times.

Here's the basic structure:

example.go
switch season {
case "spring":
    fmt.Println("Flowers blooming")
case "winter":
    fmt.Println("Time for snow")
default:
    fmt.Println("Some other season")
}

Go compares season against each case from top to bottom. When it finds a match, it runs that block and stops. Unlike C or Java, there's no fall-through and no break needed.

You can match multiple values in a single case by separating them with commas:

example.go
switch fruit {
case "apple", "pear", "cherry":
    fmt.Println("tree fruit")
case "strawberry", "blueberry":
    fmt.Println("berry")
}

The default case runs when nothing else matches. Think of it like else at the end of an if chain.

Since you already know functions, switch works great with return to send back different values:

example.go
func trafficLight(color string) string {
    switch color {
    case "red":
        return "Stop"
    case "green":
        return "Go"
    default:
        return "Unknown color"
    }
}
>_Exercise

Exercise: Day Classifier

Use a switch statement to check the value of day and return the correct classification:

  • "Monday" through "Friday""weekday"
  • "Saturday" or "Sunday""weekend"
  • Anything else → "unknown"
Stuck? Reveal a hint to help you.
Hints (0/4)
Key Takeaway
Next UpRepeating things with loops.