Go语言的 break label 和 continue label | Konica 的自留地

Go语言的 break label 和 continue label

Fantasy, Landscape, Mountains, Human, Wanderer

标号 label

for循环中break和continue只是针对最近的一重循环,但在多重循环中,可以用标号label标出想break或continue的循环。
规定标号label必须放在for循环之前,即label必须紧跟循环, 否则出现 invalid continue label 错误

示例

仔细观察a1~a4四个函数代码和程序运行结果,看看有什么不同。

Go语言代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import "fmt"
func main() {
a1()
a2()
a3()
a4()
}
func a1() {
fmt.Println("---- func a1() continue with label: ")
re:
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
continue re
}
}
}
func a2() {
fmt.Println("---- func a2() continue without label: ")
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
continue
}
}
}
func a3() {
fmt.Println("---- func a3() break with label: ")
re:
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
break re
}
}
}
func a4() {
fmt.Println("---- func a4() break without label: ")
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
break
}
}
}

运行结果

---- func a1() continue with label:
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11
---- func a2() continue without label:
i: 1
i2: 11
i2: 12
i2: 13
i: 2
i2: 11
i2: 12
i2: 13
i: 3
i2: 11
i2: 12
i2: 13
---- func a3() break with label:
i: 1
i2: 11
---- func a4() break without label:
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11