Switch
switch compares a value to cases and runs the first match, with no break needed. Several values can share a case with commas. A switch with no value works like an if chain, and fallthrough continues into the next case.
Example
day := 6
switch day {
case 1, 2, 3, 4, 5:
fmt.Println("Weekday")
case 6, 7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid")
}
score := 82
switch {
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B")
default:
fmt.Println("C")
}Result
Weekend B
Exercise
Run when no case matches.
switch x { : }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.