Control flow
switch
Go's `switch` looks like other languages', with one major difference: each `case` automatically stops after executing. No `break` needed, and no risk of accidentally falling through to the next case.
day := "mercredi" switch day {case "samedi", "dimanche": fmt.Println("Week-end")default: fmt.Println("Jour de semaine")}// affiche "Jour de semaine"A `case` can group several comma-separated values, as above for "samedi" and "dimanche". If you genuinely need the old fallthrough behavior (continue into the next case), the `fallthrough` keyword exists, but it's rarely used.
A `switch` with no expression after the keyword behaves like a more readable `if/else if`: each `case` holds its own boolean condition.
score := 82 switch {case score >= 90: fmt.Println("A")case score >= 75: fmt.Println("B")case score >= 60: fmt.Println("C")default: fmt.Println("D")}// affiche "B"There's also the "type switch" (`switch v := x.(type)`), which tests the dynamic type of an interface. It will be introduced in the interfaces module, once the concept makes sense.
Your turn
Write a `season(month int) string` function (month 1 to 12) that returns "winter", "spring", "summer", or "fall" using an expressionless `switch`.
func season(month int) string { // à compléter}