if

  1. fn main() {
  2. let number = 3;
  3. if number < 5 {
  4. println!("condition was true");
  5. } else {
  6. println!("condition was false");
  7. }
  8. }
另外值得注意的是代码中的条件 必须bool 值。如果条件不是 bool 值,我们将得到一个错误。
  1. fn main() {
  2. let number = 3;
  3. if number {
  4. println!("number was three");
  5. }
  6. }
  7. // 报错

else if

可以将 else if 表达式与 ifelse 组合来实现多重条件。
  1. fn main() {
  2. let number = 6;
  3. if number % 4 == 0 {
  4. println!("number is divisible by 4");
  5. } else if number % 3 == 0 {
  6. println!("number is divisible by 3");
  7. } else if number % 2 == 0 {
  8. println!("number is divisible by 2");
  9. } else {
  10. println!("number is not divisible by 4, 3, or 2");
  11. }
  12. }

在 let 语句中使用 if

  1. fn main() {
  2. let condition = true;
  3. let number = if condition {
  4. 5
  5. } else {
  6. 6
  7. };
  8. println!("The value of number is: {}", number);
  9. }
整个 if 表达式的值取决于哪个代码块被执行。这意味着 if 的每个分支的可能的返回值都必须是相同类型;
  1. fn main() {
  2. let condition = true;
  3. let number = if condition {
  4. 5
  5. } else {
  6. "six"
  7. };
  8. println!("The value of number is: {}", number);
  9. }
  10. // 报错
if 代码块中的表达式返回一个整数,而 else 代码块中的表达式返回一个字符串。这不可行,因为变量必须只有一个类型。Rust 需要在编译时就确切的知道 number 变量的类型,这样它就可以在编译时验证在每处使用的 number 变量的类型是有效的。Rust 并不能够在 number 的类型只能在运行时确定的情况下工作;这样会使编译器变得更复杂而且只能为代码提供更少的保障,因为它不得不记录所有变量的多种可能的类型。

使用循环重复执行

Rust 有三种循环:loopwhilefor

loop

  1. fn main() {
  2. loop {
  3. println!("again!");
  4. }
  5. }

从循环返回

  1. fn main() {
  2. let mut counter = 0;
  3. let result = loop {
  4. counter += 1;
  5. if counter == 10 {
  6. break counter * 2; // 类似return显式退出
  7. }
  8. };
  9. println!("The result is {}", result);
  10. }

while条件循环

  1. fn main() {
  2. let mut number = 3;
  3. while number != 0 {
  4. println!("{}!", number);
  5. number = number - 1;
  6. }
  7. println!("LIFTOFF!!!");
这种结构消除了很多使用 loopifelsebreak 时所必须的嵌套,这样更加清晰。当条件为真就执行,否则退出循环。

for

  1. fn main() {
  2. let a = [10, 20, 30, 40, 50];
  3. let mut index = 0;
  4. while index < 5 {
  5. println!("the value is: {}", a[index]);
  6. index = index + 1;
  7. }
  8. }
  9. // 但这个过程很容易出错;如果索引长度不正确会导致程序 panic。
  10. // 这也使程序更慢,因为编译器增加了运行时代码来对每次循环的每个元素进行条件检查。
  11. //作为更简洁的替代方案,可以使用 for 循环来对一个集合的每个元素执行一些代码。
  12. fn main() {
  13. let a = [10, 20, 30, 40, 50];
  14. for element in a.iter() {
  15. println!("the value is: {}", element);
  16. }
  17. }
  18. // 逆序遍历
  19. fn main() {
  20. for number in (1..4).rev() {
  21. println!("{}!", number);
  22. }
  23. println!("LIFTOFF!!!");
  24. }
  25. fn main() {
  26. let a = [10, 20, 30, 40, 50];
  27. for number in (0..5).rev() {
  28. println!("the value is: {}", a[number]);
  29. }
  30. }