Path/Stage 1 · Foundations

If, Else, Switch

Branching in Go — parentheses-free, braces-required.

Gopher narrator

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")
}
Exercise 1·code

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.

Plate · main.go
Loading...
Test suite · go test
  • 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.

Exercise 2·code

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.

Plate · main.go
Loading...
Test suite · go test
  • TestGradeApending
  • TestGradeMiddleBandspending
  • TestGradeFpending
Hint

switch { case cond1: ...; case cond2: ...; default: ... } — the switch value is optional; each case is a boolean expression.

Exercise 3·mcq

In Go, switch cases…