while let Statements

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

fn main() {
    let mut name = String::from("Comprehensive Rust 🦀");
    while let Some(c) = name.pop() {
        dbg!(c);
    }
    // (There are more efficient ways to reverse a string!)
}

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.

  • 指出只要值与模式匹配,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.
  • This form cannot be used as an expression, because it may have no value if the condition is false.