1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-05-29 21:57:42 +02:00
comprehensive-rust/src/control-flow/if-let-expressions.md
Igor Petruk 1c36b5d771
Update if-let-expressions.md (#237)
Mention `let else` in the speaker notes.
2023-01-23 10:05:06 -08:00

843 B

if let expressions

If you want to match a value against a pattern, you can use if let:

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

See pattern matching for more details on patterns in Rust.

  • if let can be more concise than match, e.g., when only one case is interesting. In contrast, match requires all branches to be covered.
    • For the similar use case consider demonstrating a newly stabilized let else feature.
  • A common usage is handling Some values when working with Option.
  • Unlike match, if let does not support guard clauses for pattern matching.