我知道 switch
/select
语句在每个 case 之后都会自动中断。我想知道,在以下代码中:
for {
switch sometest() {
case 0:
dosomething()
case 1:
break
default:
dosomethingelse()
}
}
break
语句是退出 for
循环还是仅退出 switch
block ?
最佳答案
Break statements, The Go Programming Language Specification.
A "break" statement terminates execution of the innermost "for", "switch" or "select" statement.
BreakStmt = "break" [ Label ] .
If there is a label, it must be that of an enclosing "for", "switch" or "select" statement, and that is the one whose execution terminates (§For statements, §Switch statements, §Select statements).
L: for i < n { switch i { case 5: break L } }
因此,您示例中的 break
语句终止了 switch
语句,即“最内层”语句。
关于select - break 语句是否从 switch/select 中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11104085/