都知道goto
不可亵玩焉,逻辑跳跃,不易维护云云。
但存在深层嵌套的场景下,continue break goto
配合label的合理使用,也不失为简化代码逻辑的好方法
Goto statements
A “goto” statement transfers control to the statement with the corresponding label within the same function.
Continue statements
A “continue” statement begins the next iteration of the innermost “for” loop at its post statement. The “for” loop must be within the same function.
Break statements
A “break” statement terminates execution of the innermost “for”, “switch”, or “select” statement within the same function.
如果不配合label,直接使用break和continue,则只在终止或跳过当前循环
代码示例
1 | func main() { |
break和continue的label必须写在代码块的前面
其中,break label 将直接跳出循环,即不再执行label所标记的循环
而continue label 则将继续执行循环,即开始下一次循环
输出
1 | index 1 |