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
.
// Convert hexadecimal character to an int value
switch { 1
case '0' <= c && c <= '9': 2
return c - '0' 3
case 'a' <= c && c <= 'f': 4
return c - 'a' + 10
case 'A' <= c && c <= 'F': 5
return c - 'A' + 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.
switch i {
case 0: fallthrough
case 1: 1
f()
default:
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:
switch i {
case 0, 1: 1
f()
default:
g()
You can list cases on one line 1, separated by commas.