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!
     */
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青衫客36

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值