switch Statement
Start with Go switch Statement
A switch statement selects a branch based on a value or a set of conditions. It often reads more clearly than a long chain of checks for the same expression.
What you’ll learn
- Use expression and default cases.
- Group cases for the same output.
- Understand no automatic fallthrough.
Understand the idea
In an expression switch, Go compares the switch expression with each case value. Once a matching case runs, it exits the switch automatically; most switches need no break. A default clause handles unmatched values.
You can list several matching values in one case, separated by commas. A switch without an expression is also valid and checks boolean conditions in order.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
day := "Sunday"
switch day {
case "Saturday", "Sunday":
fmt.Println("Weekend")
case "Monday":
fmt.Println("Start of the week")
default:
fmt.Println("Weekday")
}
}
Output
WeekendTrace what the program does
The value Sunday matches the first case, which lists two possible strings. Go prints Weekend and exits the switch without executing any other cases. It does not fall through by default.
Avoid common mistakes
- Unlike C-style switches, Go cases do not automatically fall through.
- Cases can be grouped with commas;
case "Saturday" || "Sunday"is not valid for switching on a string.
Try it yourself
Change the day to Tuesday and predict which clause runs. Add a case for Friday with a new message.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go switch Statement in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.