let 控制流

Rust 有几个与其他语言不同的控制流结构。它们用于模式匹配:

  • if let 表达式
  • while let expressions
  • match 表达式

if let 表达式

if let 表达式 能让你根据某个值是否与模式相匹配来执行不同的代码:

  1. use std::time::Duration;
  2. fn sleep_for(secs: f32) {
  3. if let Ok(dur) = Duration::try_from_secs_f32(secs) {
  4. std::thread::sleep(dur);
  5. println!("slept for {:?}", dur);
  6. }
  7. }
  8. fn main() {
  9. sleep_for(-10.0);
  10. sleep_for(0.8);
  11. }

let else expressions

如需了解匹配模式并从函数返回的常见情况,请使用 let else。”else” 分支必须执行不同的结束方式(例如,returnbreakpanic,但不能直接执行到代码块的末尾)。

  1. fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> {
  2. let s = if let Some(s) = maybe_string {
  3. s
  4. } else {
  5. return Err(String::from("got None"));
  6. };
  7. let first_byte_char = if let Some(first_byte_char) = s.chars().next() {
  8. first_byte_char
  9. } else {
  10. return Err(String::from("got empty string"));
  11. };
  12. if let Some(digit) = first_byte_char.to_digit(16) {
  13. Ok(digit)
  14. } else {
  15. Err(String::from("not a hex digit"))
  16. }
  17. }
  18. fn main() {
  19. println!("result: {:?}", hex_or_die_trying(Some(String::from("foo"))));
  20. }

if let 一样,while let 变体会针对一个模式重复测试一个值:

  1. fn main() {
  2. let mut name = String::from("Comprehensive Rust 🦀");
  3. while let Some(c) = name.pop() {
  4. println!("character: {c}");
  5. }
  6. // (There are more efficient ways to reverse a string!)
  7. }

Here String::pop returns Some(c) until the string is empty, after which it will return None. The while let lets us keep iterating through all items.

This slide should take about 10 minutes.

if-let

  • Unlike match, if let does not have to cover all branches. This can make it more concise than match.
  • 使用 Option 时,常见的做法是处理 Some 值。
  • match 不同的是,if let 不支持模式匹配的 guard 子句。

let-else

if-lets can pile up, as shown. The let-else construct supports flattening this nested code. Rewrite the awkward version for students, so they can see the transformation.

重写后的版本为:

  1. #![allow(unused)]
  2. fn main() {
  3. fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> {
  4. let Some(s) = maybe_string else {
  5. return Err(String::from("got None"));
  6. };
  7. let Some(first_byte_char) = s.chars().next() else {
  8. return Err(String::from("got empty string"));
  9. };
  10. let Some(digit) = first_byte_char.to_digit(16) else {
  11. return Err(String::from("not a hex digit"));
  12. };
  13. return Ok(digit);
  14. }
  15. }

while-let

  • 指出只要值与模式匹配,while let 循环就会一直进行下去。
  • You could rewrite the while let loop as an infinite loop with an if statement that breaks when there is no value to unwrap for name.pop(). The while let provides syntactic sugar for the above scenario.