Rust- if let & while let

if let and while let are control flow constructs in Rust that combine if or while with pattern matching. They can be particularly useful when dealing with enums and Option types.

  1. if let:

if let allows you to combine if and let into a less verbose way to handle values that match a specific pattern and ignore the rest. Here is an example:

let some_option_value: Option<i32> = Some(5);

if let Some(x) = some_option_value {
    println!("{}", x);
}

In this case, if some_option_value is Some, it gets unwrapped, and the inner value gets bound to x. If it’s None, nothing happens. This is more concise than using a match statement when you only care about one of the variants.

  1. while let:

while let is similar but it works as a while loop. It continues to loop as long as the pattern continues to match:

let mut stack = Vec::new();

stack.push(1);
stack.push(2);
stack.push(3);

while let Some(top) = stack.pop() {
    println!("{}", top);
}

In this example, stack.pop() removes the last element from the vector and returns Some(value). If the stack is empty, it returns None. The while let loop continues popping values off the stack and printing them until the stack is empty.

These constructs provide a nice way to write shorter, more readable code in situations where you want to do something with some variant of an enum, and nothing or just something simple in the other case.

A comprehensive case is as follows:

fn main() {
    let s = Some("Rust");
    let s1: Option<i32> = None;
    let s2: Option<i32> = None;

    // 如果let将s解构成Some(i), 则执行语句块{}
    if let Some(i) = s {
        println!("已上车{:?}", i); // 已上车"Rust"
    }

    // 如果解构失败,就执行else
    if let Some(i) = s1 {
        println!("Matched {:?}", i)
    } else {
        println!("不匹配") // 不匹配
    }

    let flag = false;
    if let Some(i) = s2 {
        println!("Matched {:?}", i);
    } else if flag {
        println!("不匹配s2")
    } else {
        println!("默认分支") // 默认分支
    }

    let mut num = Some(0);

    while let Some(i) = num {
        if i > 9 {
            println!("{}, quit!", i);
            num = None;
        } else {
            println!("i is {:?} Try again", i);
            num = Some(i + 1);
        }
    }

    /*
        输出:
        i is 0 Try again
        i is 1 Try again
        i is 2 Try again
        i is 3 Try again
        i is 4 Try again
        i is 5 Try again
        i is 6 Try again
        i is 7 Try again
        i is 8 Try again
        i is 9 Try again
        10, quit!
     */
}

你可能感兴趣的:(Rust,rust)