04. 标签跳转语句 (label)
Label 标签在 Shell 中没有。 但在 Go 中却应用广泛。
Label 的定义规则为 SomeName: , 以 : 结尾。
在 Go 使用 Label 必须使用配置关键字 continue, break, goto 的其中一个。
需要注意的是,
continue和break的Label可以省略。continue|break [Label]goto必须配置Laebl使用。goto Label
- 直接使用
continue/break的时候, 作用域在 当前代码体 中。 如果配合了Label就可以跳出到 当前代码体外。 - 在配合
for/select/switch使用时,Label必须 紧临 他们, 中间不能有任何其他语句。
func continueBreakDemo() {
Outer:
for m := 1; m < 10; m++ {
Inner:
for n := 1; n < 10; n++ {
fmt.Printf("%d*%d=%d ", m, n, m*n)
if n == 3 {
break Outer
}
if n%4 == 0 {
break Inner
}
}
fmt.Println("")
}
}
// Output:
// 1*1=1 1*2=2 1*3=3
在配置 goto 使用的时候, Label 的位置没有特别要求。 即可以在被 调用前或后。
func gotoLabel(n int) {
fmt.Println("刚开始")
goto End
fmt.Println("是奇数") // 永远不会执行, IDE 也提示对应提示
End:
fmt.Println("结束啦")
}