If, Else, Switch
Branching in Go — parentheses-free, braces-required.
Have the gopher read this explanation out loud.
No parentheses around the condition; braces are always required. switch in Go does not fall through by default, so no break is needed, and a single case can list several values.
if x > 0 {
fmt.Println("positive")
} else if x == 0 {
fmt.Println("zero")
} else {
fmt.Println("negative")
}
switch day {
case "Sat", "Sun":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}Implement classify(n int) string returning the FizzBuzz label: "FizzBuzz" when n is divisible by 15, "Fizz" when divisible by 3, "Buzz" when divisible by 5, otherwise the number as a string (use strconv.Itoa). A hidden test suite exercises it.
- TestClassifyFizzBuzzpending
- TestClassifyFizzpending
- TestClassifyBuzzpending
- TestClassifyNumberpending
Hint
Check divisibility by 15 first, since 15 is also divisible by 3 and 5. n%15 == 0 uses the modulo operator.
Implement grade(score int) string using a switch statement (no if chain): 90+ = "A", 80-89 = "B", 70-79 = "C", 60-69 = "D", below 60 = "F". A hidden test suite covers each band and the boundaries.
- TestGradeApending
- TestGradeMiddleBandspending
- TestGradeFpending
Hint
switch { case cond1: ...; case cond2: ...; default: ... } — the switch value is optional; each case is a boolean expression.
In Go, switch cases…