if let 表达式

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

fn main() {
    let arg = std::env::args().next();
    if let Some(value) = arg {
        println!("Program name: {value}");
    } else {
        println!("Missing name?");
    }
}

如需详细了解 Rust 中 的模式,请参阅模式匹配

  • 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 子句。

  • Since 1.65, a similar let-else construct allows to do a destructuring assignment, or if it fails, execute a block which is required to abort normal control flow (with panic/return/break/continue):

    fn main() {
        println!("{:?}", second_word_to_upper("foo bar"));
    }
     
    fn second_word_to_upper(s: &str) -> Option<String> {
        let mut it = s.split(' ');
        let (Some(_), Some(item)) = (it.next(), it.next()) else {
            return None;
        };
        Some(item.to_uppercase())
    }