switch statement
suggest changeA simple switch
statement:
a := 1
switch a {
case 1, 3:
fmt.Printf("a is 1 or 3\n")
case 2:
fmt.Printf("a is 2\n")
default:
fmt.Printf("default: a is %d\n", a)
}
a is 1 or 3
Notice case
can handle multiple values (1
and 3
in above example).
fallthrough
Unlike most other languages like C++ or Java, you don't have to use break
to stop one case
into continuing execution in following case
.
Such default behavior is a frequent source of bugs.
Instead in Go you can ask for such behavior with fallthrough
:
a := 1
switch a {
case 1:
fmt.Printf("case 1\n")
fallthrough
case 2:
fmt.Printf("caes 2\n")
}
case 1
caes 2
switch on strings
Switch in Go is more flexible than in languages like C++ or Java.
We can switch
on strings:
s := "foo"
switch s {
case "foo":
fmt.Printf("s is 'foo'\n")
case "bar":
fmt.Printf("s is 'bar'\n")
}
s is 'foo'
empty switch expression
switch
expression can be empty in which case case
can be a boolean expression, not just a constant:
func check(n int) {
switch {
case n > 0 && n%3 == 0:
fmt.Printf("n is %d, divisible by 3\n", n)
case n >= 4:
fmt.Printf("n is %d (>= 4)\n", n)
default:
fmt.Printf("default: n is %d\n", n)
}
}
check(3)
check(4)
check(6)
check(1)
n is 3, divisible by 3
n is 4 (>= 4)
n is 6, divisible by 3
default: n is 1
order of evaluation of case
What happens if more than one case
statement evaluates as true?
In the above example 6
matches both n > 0 && n%3 == 0
expression and n ≥ 4
expression.
As you can see, only one case
is executed, the one defined first.
assignment in switch
switch n := rand.Intn(9); n {
case 1, 2, 3:
fmt.Printf("case 1, 2, 3: n is %d\n", n)
case 4, 5:
fmt.Printf("case 4, 5: n is %d\n", n)
default:
fmt.Printf("default: n is %d\n", n)
}
case 4, 5: n is 4
switch on type
If you have an interface value, you can switch based on type of underlying value:
func printType(iv interface{}) {
// inside case statements, v is of type matching case type
switch v := iv.(type) {
case int:
fmt.Printf("'%d' is of type int\n", v)
case string:
fmt.Printf("'%s' is of type string\n", v)
case float64:
fmt.Printf("'%f' is of type float64\n", v)
default:
fmt.Printf("We don't support type '%T'\n", v)
}
}
func main() {
printType("5")
printType(4)
printType(true)
}
'5' is of type string
'4' is of type int
We don't support type 'bool'