参考:https://kaisery.github.io/trpl-zh-cn/ch03-05-control-flow.htmlhttps://doc.rust-lang.org/book/ch03-05-control-flow.html

if 表达式

  1. if cond { // 无需 `()` 括号
  2. // todo
  3. }

或者

  1. if cond {
  2. // todo
  3. } else {
  4. // todo
  5. }

或者

  1. if cond1 && cond2 {
  2. // todo
  3. } else if cond3 || cond4 {
  4. // todo
  5. } else {
  6. // todo
  7. }

cond 必须是显示的 bool。Rust 并不会尝试自动地将非布尔值转换为布尔值。比如 0、1等任何数字都不是 cond 需要的布尔值。
所以如果有多于一个 else if 表达式,最好使用分支结构(branching construct)match 来重构代码。
由于 if 是一个表达式,所以 可以在 let 语句的右侧使用它:注意最后的 ;let 赋值语句的结尾,不是 if 表达式或者 {} 代码块的结尾

  1. let number = if true {
  2. 1
  3. } else {
  4. 0 // 分支返回的结果必须是同一类型,否则无法通过编译
  5. };

if-else 条件选择是一个表达 式,并且所有分支都必须返回相同的类型。

loop 重复执行代码

  1. 基本模式:终端用 Ctrl-C 停止程序,或者使用 break;语句跳出loop

    1. loop {
    2. // 语句
    3. break;
    4. }

    也可以在中途使用 continue 来跳过这次循环的剩下内容。
    在跳出 loop 需要返回值时,则把值的表达式放在 break 后面,即 break 表达式; ,则表达式就会被 loop 返回,例如:

    1. loop {
    2. // 语句
    3. break 1; // 跳出时返回 1
    4. }
  2. 在处理嵌套循环的时候可以breakcontinue外层循环。在这类情形中,循环必须 用一些'label(标签)来注明,并且标签必须传递给break/continue语句。

    1. // src: https://rustwiki.org/zh-CN/rust-by-example/flow_control/loop/nested.html
    2. #![allow(unreachable_code)]
    3. fn main() {
    4. 'outer: loop {
    5. println!("Entered the outer loop");
    6. 'inner: loop {
    7. println!("Entered the inner loop");
    8. // 这只是中断内部的循环
    9. //break;
    10. // 这会中断外层循环
    11. break 'outer;
    12. }
    13. println!("This point will never be reached");
    14. }
    15. println!("Exited the outer loop");
    16. }

    while 条件循环

    基本模式:

    1. while cond {
    2. // 语句
    3. }

    当条件为真,执行循环。当条件不再为真,可调用 break 停止循环。
    这中循环类型可以通过组合 loopifelsebreak 来实现;另一个角度看,消除了很多使用它们时所必须的嵌套。
    经典例子:倒计时

    1. fn main() {
    2. let mut number = 3;
    3. while number != 0 {
    4. println!("{}!", number);
    5. number = number - 1;
    6. }
    7. }

    for 遍历集合

  3. 基本模式:

    1. for element in one_collect {
    2. // 语句
    3. }

    相比于 whilefor 消除了可能由于超出数组的结尾或遍历长度不够而缺少一些元素而导致的 bug。
    for 循环的安全性和简洁性使得它成为 Rust 中使用最多的循环结构。
    重现倒计时:这里使用了 range 类型

    1. fn main() {
    2. for number in (1..4).rev() { // 如果需要包含右端点,则使用等号: 1..=4
    3. println!("{}!", number);
    4. }
    5. }
  4. for ... in iterator :如果没有特别指定,for 循环会对给出的集合应用 into_iter 函数,把它转换成 一个迭代器。

  • iter:在每次迭代中借用集合中的一个元素。这样集合本身不会被改变,循环之后仍 可以使用。
  • into_iter:会消耗集合。在每次迭代中,集合中的数据本身会被提供。一旦集合被消耗了,之后就无法再使用了,因为它已经在循环中被 “移除”(move)了。
  • iter_mut:可变地(mutably)借用集合中的每个元素,从而允许集合被就地修改。

    总结

    你做到了!这是一个大章节:你学习了变量、标量和复合数据类型、函数、注释、 if 表达式和循环!如果你想要实践本章讨论的概念,尝试构建如下程序:

  • 相互转换摄氏与华氏温度。

  • 生成 n 阶斐波那契数列。
  • 打印圣诞颂歌 “The Twelve Days of Christmas” 的歌词,并利用歌曲中的重复部分(编写循环)。

当你准备好继续的时候,让我们讨论一个其他语言中 并不 常见的概念:所有权(ownership)。
其他 2:一些书中的练习