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 不會為模式比對支援成立條件子句。

  • 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())
    }