Lesson 7 · 7 of 20
Choosing with switch · Go
Choose between several cases with switch in Go: several values per case, default, switch with no expression, init statement and fallthrough.

switch compares a value with several cases and runs the first one that matches. switch day looks at the value of day; a case can list several values separated by commas, like "Saturday", "Sunday", and default runs when none of them matches.
Unlike C or JavaScript, in Go each case ends on its own: there is no need for break, and execution never slips into the next case by accident.
A switch with no value is a tidier way to write a chain of if and else if: each case holds a condition and the first true one wins. With 82 points score >= 90 does not hold, but score >= 80 does, so the grade is a B.
Like if, switch accepts an init statement: switch level := 2; level. And if you really want to carry on into the next case, you have to ask for it with fallthrough: after level 2, case 1 runs too, without being checked.
Code · main.go
package mainimport "fmt"func main() { day := "Saturday" // Each case ends on its own: no break needed. switch day { case "Saturday", "Sunday": fmt.Println(day, "is weekend") default: fmt.Println(day, "is a working day") } // With no value, switch works like a chain of if / else. score := 82 switch { case score >= 90: fmt.Println(score, "-> grade A") case score >= 80: fmt.Println(score, "-> grade B") default: fmt.Println(score, "-> grade C") } // An init statement, and fallthrough to run the next case too. switch level := 2; level { case 2: fmt.Println("Level 2: bonus unlocked") fallthrough case 1: fmt.Println("Level 1: basics done") }}Output · go run main.go
Saturday is weekend 82 -> grade B Level 2: bonus unlocked Level 1: basics done
Key points
switch valuelooks for the first matchingcase.- A
casecan list several values separated by commas. - No
breakneeded;fallthroughmoves on to the next case. switchwith no value replaces anif/else ifchain.defaultruns when no case matches.
Exercise
Write a switch on a month number (1 to 12) that prints the season (winter, spring, summer or autumn), with several months in each case and a default for invalid numbers.