forked from unknwon/the-way-to-go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
17 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,21 @@ | ||
#5.0 控制结构 | ||
到目前,我们已经看到了在main()方法中Go程序按照方法中的语句的开始顺序执行.通常,只有当一个条件满足时,我们才执行相应的语句.因此Go提供了下面的条件分支结构. | ||
if else 结构 | ||
switch else 结构 | ||
select 结构 channels间切换(见14.4) | ||
到目前为止,我们看到的都是 Go 程序都是从 main() 函数开始执行,然后按顺序执行该函数体中的代码。但我们经常会需要只有在满足一些特定情况时才执行某些代码,也就是说在代码里进行条件判断。针对这种需求,Go 提供了下面这些条件结构和分支结构: | ||
|
||
if-else 结构 | ||
switch-else 结构 | ||
select 结构,用于 channel 的选择(第 14.4 节) | ||
|
||
可以使用迭代或循环结构来重复执行一次或多次某段代码(任务): | ||
|
||
重复执行一个任务一次或多次,可以使用迭代或循环结构: | ||
for (range) 结构 | ||
其他的关键词像break和continue可以改变循环. | ||
还有return关键词,/*从语句主体中直接返回*/和goto关键词跳转执行label所在处的代码 | ||
Go完全忽略了if,swaitch,for等周围的括号(),比java,c++,c#减少的视觉上的代码混乱,让代码看起来更简洁. | ||
|
||
一些如 `break` 和 `continue` 这样的关键字可以用于中途改变循环的状态。 | ||
|
||
此外,你还可以使用 `return` 来结束某个函数的执行,或使用 `goto` 和标签来调整程序的执行位置。 | ||
|
||
Go 完全省略了 `if`、`switch` 和 `for` 结构中条件语句两侧的括号,相比 Java、C++ 和 C# 中减少了很多视觉混乱的因素,同时也使你的代码更加简洁。 | ||
|
||
##链接 | ||
- [目录](directory.md) | ||
- 上一章:[基本结构和基本数据类型](04.0.md) | ||
- 下一节: [if else 结构](05.1.md) | ||
- 上一章:[指针](04.9.md) | ||
- 下一节: [if-else 结构](05.1.md) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters