I know that switch
/select
statements break automatically after every case. I am wondering, in the following code:
for {
switch sometest() {
case 0:
dosomething()
case 1:
break
default:
dosomethingelse()
}
}
Does the break
statement exit the for
loop or just the switch
block?
Just from a switch block. There's plenty of examples in Golang own code you can examine (compare inner break with outer break).
It only exits the switch block.
Therefore, the
break
statement in your example terminates theswitch
statement, the "innermost" statement.this should explain it.
Runs forever
Again, runs forever
BUT
will print sjus ... clear ?
http://play.golang.org/p/GOvnfI67ih
Yes,
break
breaks the innerswitch
.https://play.golang.org/p/SZdDuVjic4
Another use of break for switch is in combination with fallthrough statement. It might need some creativity to use it properly in correct situation, but it is possibly a usable combination.
Here is simple example: