let-else

🛈 自 rust 1.65 版本起稳定

🛈 你可以通过像这样编译来指定特定的版本:rustc --edition=2021 main.rs

使用 let-else,一个可反驳的模式可以像普通的 let 一样匹配并在周围作用域中绑定变量,或者当模式不匹配时发散(例如,breakreturnpanic!)。

use std::str::FromStr;

fn get_count_item(s: &str) -> (u64, &str) {
    let mut it = s.split(' ');
    let (Some(count_str), Some(item)) = (it.next(), it.next()) else {
        panic!("Can't segment count item pair: '{s}'");
    };
    let Ok(count) = u64::from_str(count_str) else {
        panic!("Can't parse integer: '{count_str}'");
    };
    (count, item)
}

fn main() {
    assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
}

名称绑定的作用域是它与 matchif let-else 表达式的主要区别。之前,你可以通过一些不必要的重复和一个外部的 let 来近似这些模式。

#![allow(unused)]
fn main() {
use std::str::FromStr;

fn get_count_item(s: &str) -> (u64, &str) {
    let mut it = s.split(' ');
    let (count_str, item) = match (it.next(), it.next()) {
        (Some(count_str), Some(item)) => (count_str, item),
        _ => panic!("Can't segment count item pair: '{s}'"),
    };
    let count = if let Ok(count) = u64::from_str(count_str) {
        count
    } else {
        panic!("Can't parse integer: '{count_str}'");
    };
    (count, item)
}

assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
}

另请参阅

option, match, if let 以及 let-else RFC