Switch

Go’s switch is very flexible; you can match on muchmore than just integers. The cases are evaluated top to bottom until a match isfound, and if the switch has no expression it switches on true. It’stherefore possible – and idiomatic – to write an if-else-if-else chain asa switch.

  1. // Convert hexadecimal character to an int value
  2. switch { 1
  3. case '0' <= c && c <= '9': 2
  4. return c - '0' 3
  5. case 'a' <= c && c <= 'f': 4
  6. return c - 'a' + 10
  7. case 'A' <= c && c <= 'F': 5
  8. return c - 'A' + 10
  9. }
  10. return 0

A switch without a condition is the same as switch true 1. We list thedifferent cases. Each case statement has a condition that is either true offalse. Here 2 we check if c is a number. If c is a number we return itsvalue 3. Check if c falls between “a” and “f” 4. For an “a” wereturn 10, for “b” we return 11, etc. We also do the same 5 thing for “A”to “F”.

There is no automatic fall through, you can use fallthrough for that.

  1. switch i {
  2. case 0: fallthrough
  3. case 1: 1
  4. f()
  5. default:
  6. g() 2

f() can be called when i == 0 1. With default youcan specify an action when none of the other cases match. Here g() is calledwhen i is not 0 or 1 2. We could rewrite the above example as:

  1. switch i {
  2. case 0, 1: 1
  3. f()
  4. default:
  5. g()

You can list cases on one line 1, separated by commas.