Files
the-way-to-go_ZH_CN/eBook/05.5.md

78 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 5.5 Break 与 continue
您可以使用 break 语句重写 for2.go 的代码:
示例 5.10 [for3.go](examples/chapter_5/for3.go)
```go
for {
i = i - 1
fmt.Printf("The variable i is now: %d\n", i)
if i < 0 {
break
}
}
```
因此每次迭代都会对条件进行检查i < 0以此判断是否需要停止循环如果退出条件满足则使用 break 语句退出循环
一个 break 的作用范围为该语句出现后的最内部的结构它可以被用于任何形式的 for 循环计数器条件判断等)。但在 switch select 语句中详见第 13 break 语句的作用结果是跳过整个代码块执行后续的代码
下面的示例中包含了嵌套的循环体for4.gobreak 只会退出最内层的循环
示例 5.11 [for4.go](examples/chapter_5/for4.go)
```go
package main
func main() {
for i:=0; i<3; i++ {
for j:=0; j<10; j++ {
if j>5 {
break
}
print(j)
}
print(" ")
}
}
```
输出
012345 012345 012345
关键字 continue 忽略剩余的循环体而直接进入下一次循环的过程但不是无条件执行下一次循环执行之前依旧需要满足循环的判断条件
示例 5.12 [for5.go](examples/chapter_5/for5.go)
```go
package main
func main() {
for i := 0; i < 10; i++ {
if i == 5 {
continue
}
print(i)
print(" ")
}
}
```
输出
```
0 1 2 3 4 6 7 8 9
```
显然5 被跳过了
另外关键字 continue 只能被用于 for 循环中
## 链接
- [目录](directory.md)
- 上一节[for 结构](05.4.md)
- 下一节[标签与 goto](05.6.md)