Switch-Case Statements in Go
When your if-else chains start getting long and messy, switch is the cleaner way to handle multiple choices.
Also available on YouTube • 14:04 watch time
When If-Else Gets Ugly
Imagine you're building a menu with five options. You could write five if-else-if blocks, but it gets hard to read fast. Switch gives you a clean, structured way to say: "Look at this value and jump to the matching case."
The Basic Switch
day := "Tuesday"
switch day {
case "Monday":
fmt.Println("Start of the work week.")
case "Tuesday":
fmt.Println("Second day — keep going!")
case "Friday":
fmt.Println("Almost weekend!")
default:
fmt.Println("Just another day.")
}
Go compares day against each case. When it finds a match, it runs that block and stops. No need for break statements — Go handles that automatically. If nothing matches, the default case runs.
Multiple Values in One Case
You can group related values together with commas:
day := "Saturday"
switch day {
case "Saturday", "Sunday":
fmt.Println("It's the weekend!")
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
fmt.Println("It's a weekday.")
}
This keeps things compact when several values should trigger the same response.
Switch Without a Value
Here's something cool — you can use switch without comparing a specific variable. Each case becomes its own condition:
temperature := 35
switch {
case temperature > 30:
fmt.Println("It's hot outside!")
case temperature > 15:
fmt.Println("Nice and warm.")
default:
fmt.Println("Better grab a jacket.")
}
This is essentially a cleaner way to write a chain of if-else-if blocks. Many Go developers prefer this style for readability.
No fallthrough by default: In languages like C or Java, forgetting a break in a switch causes bugs where multiple cases run. Go doesn't have this problem — each case automatically stops after running. If you actually want fallthrough, you have to explicitly write fallthrough.
Try It Yourself
Write a program that takes a grade letter (A, B, C, D, F) and prints a message for each one. Use a switch statement instead of if-else. Then try the "switch without a value" form using a numeric score.