Files
the-way-to-go_ZH_CN/eBook/05.5.md
Haigang Zhou f5dae8f559 4-5 章 (#844)
Co-authored-by: Joe Chen <jc@unknwon.io>
2022-05-09 21:42:14 +08:00

78 lines
1.7 KiB
Markdown
Raw Permalink 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](examples/chapter_5/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 章](13.0.md)`break` 语句的作用结果是跳过整个代码块,执行后续的代码。
下面的示例中包含了嵌套的循环体for4.go`break` 只会退出最内层的循环:
示例 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)