-
Notifications
You must be signed in to change notification settings - Fork 0
Go break & continue in switch
kuchaguangjie edited this page Jul 25, 2018
·
1 revision
switch
in Go, is a bit different from C or Java, one obvious difference is break
.
Rules:
-
break
is not needed for each case.
Because go's switch stops on first matching, won't execute the following ones. - If
break
is added in acase
ordefault
.
Then it will terminate the switch statement.
Rules:
-
continue
can't be applied on switch statement. - If the switch is within a loop, then a
continue
could be added, to apply on the outer loop. - If the switch is not within a loop, then can't add a
continue
inside it, it's syntax error.
switch_learn.go:
package main
import (
"fmt"
)
// check how "break" works on switch,
func breakTest() {
outer:
for i := 0; i < 10; i++ {
switch i {
case 3, 6, 9:
fmt.Printf("%d, printable by 3\n", i)
case 0, 5:
fmt.Printf("%d, printable by 5\n", i)
case 4:
break // this will break the switch, not the outer for,
case 8:
break outer // this will break the outer loop,
default:
fmt.Printf("%d, other\n", i)
}
}
}
func main() {
breakTest()
}
Execute:
go run switch_learn.go
Output:
0, printable by 5
1, other
2, other
3, printable by 3
5, printable by 5
6, printable by 3
7, other
Explanation:
-
4
is not printed, due to the firstbreak
, it terminate thatswitch
, but not the outerfor
loop. -
8
and9
is not printed, due to the secondbreak outer
, it terminate the outerfor
loop, not just theswitch
.