参考:https://kaisery.github.io/trpl-zh-cn/ch03-05-control-flow.html、https://doc.rust-lang.org/book/ch03-05-control-flow.html
if 表达式
if cond { // 无需 `()` 括号// todo}
或者
if cond {// todo} else {// todo}
或者
if cond1 && cond2 {// todo} else if cond3 || cond4 {// todo} else {// todo}
cond 必须是显示的 bool。Rust 并不会尝试自动地将非布尔值转换为布尔值。比如 0、1等任何数字都不是 cond 需要的布尔值。
所以如果有多于一个 else if 表达式,最好使用分支结构(branching construct)match 来重构代码。
由于 if 是一个表达式,所以 可以在 let 语句的右侧使用它:注意最后的 ; 是 let 赋值语句的结尾,不是 if 表达式或者 {} 代码块的结尾
let number = if true {1} else {0 // 分支返回的结果必须是同一类型,否则无法通过编译};
if-else 条件选择是一个表达 式,并且所有分支都必须返回相同的类型。
loop 重复执行代码
基本模式:终端用
Ctrl-C停止程序,或者使用break;语句跳出looploop {// 语句break;}
也可以在中途使用
continue来跳过这次循环的剩下内容。
在跳出loop需要返回值时,则把值的表达式放在break后面,即break 表达式;,则表达式就会被loop返回,例如:loop {// 语句break 1; // 跳出时返回 1}
在处理嵌套循环的时候可以
break或continue外层循环。在这类情形中,循环必须 用一些'label(标签)来注明,并且标签必须传递给break/continue语句。// src: https://rustwiki.org/zh-CN/rust-by-example/flow_control/loop/nested.html#![allow(unreachable_code)]fn main() {'outer: loop {println!("Entered the outer loop");'inner: loop {println!("Entered the inner loop");// 这只是中断内部的循环//break;// 这会中断外层循环break 'outer;}println!("This point will never be reached");}println!("Exited the outer loop");}
while 条件循环
基本模式:
while cond {// 语句}
当条件为真,执行循环。当条件不再为真,可调用
break停止循环。
这中循环类型可以通过组合loop、if、else和break来实现;另一个角度看,消除了很多使用它们时所必须的嵌套。
经典例子:倒计时fn main() {let mut number = 3;while number != 0 {println!("{}!", number);number = number - 1;}}
for 遍历集合
基本模式:
for element in one_collect {// 语句}
相比于
while,for消除了可能由于超出数组的结尾或遍历长度不够而缺少一些元素而导致的 bug。for循环的安全性和简洁性使得它成为 Rust 中使用最多的循环结构。
重现倒计时:这里使用了range类型fn main() {for number in (1..4).rev() { // 如果需要包含右端点,则使用等号: 1..=4println!("{}!", number);}}
for ... in iterator:如果没有特别指定,for循环会对给出的集合应用into_iter函数,把它转换成 一个迭代器。
iter:在每次迭代中借用集合中的一个元素。这样集合本身不会被改变,循环之后仍 可以使用。into_iter:会消耗集合。在每次迭代中,集合中的数据本身会被提供。一旦集合被消耗了,之后就无法再使用了,因为它已经在循环中被 “移除”(move)了。iter_mut:可变地(mutably)借用集合中的每个元素,从而允许集合被就地修改。总结
你做到了!这是一个大章节:你学习了变量、标量和复合数据类型、函数、注释、
if表达式和循环!如果你想要实践本章讨论的概念,尝试构建如下程序:相互转换摄氏与华氏温度。
- 生成 n 阶斐波那契数列。
- 打印圣诞颂歌 “The Twelve Days of Christmas” 的歌词,并利用歌曲中的重复部分(编写循环)。
当你准备好继续的时候,让我们讨论一个其他语言中 并不 常见的概念:所有权(ownership)。
其他 2:一些书中的练习
