Go - Switch

Beginner 10/10 Teacher 10/10 Architect 10/10

Switch

switch day {
case "Mon", "Tue":
  fmt.Println("work")
case "Sat", "Sun":
  fmt.Println("rest")
default:
  fmt.Println("?" )
}

Type Switch

switch v := i.(type) {
case int:
  fmt.Println("int", v)
case string:
  fmt.Println("string", v)
}

Common errors

  • Expecting implicit fallthrough like C—Go does not fall through by default.
  • Using non-constant types in case labels incorrectly; ensure types match.

Practice

  • Write a switch that maps weekday names to “workday” or “weekend”.

Quick quiz

  1. How do you opt into fallthrough for a case?
Show answer Use the fallthrough keyword at the end of the case block.