if let Expressions

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

use std::time::Duration;

fn sleep_for(secs: f32) {
    let result = Duration::try_from_secs_f32(secs);

    if let Ok(duration) = result {
        std::thread::sleep(duration);
        println!("slept for {duration:?}");
    }
}

fn main() {
    sleep_for(-10.0);
    sleep_for(0.8);
}
  • 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 子句。
  • With an else clause, this can be used as an expression.