Skip to main content

Switch Statement

Switch Statement

Switch in Go is pretty nice, it function similar to the switch statement in C but better.

x := 20

switch x {
  case 10, 20:
    fmt.Println("It is either 10 or 20")
  default:
    fmt.Println("It is not 10 and is not 20")
}

You can put case on multiple values rather than only just one. In addition, the default case is not mandatory, you can leave it out of your program.

Switch on conditions

Furthermore, instead of switching on a value, in the previous example it was switching on the variable x however, if you leave the value to switch on out, you can switch on other variables conditionally.

x := 22

switch {
  case x > 10:
      fmt.Println("It is greater than 10")
  case x < 10:
      fmt.Println("It is less than 10")
  case x == 10:
      fmt.Println("It is equal to 10!")
}