21.15 if let
Chains (Rust 2024+)
Stabilized in the Rust 2024 Edition, if let
chains (previously known as let_chains
) allow combining multiple if let
patterns and regular boolean conditions within a single if
statement using the logical AND operator (&&
).
21.15.1 Motivation
Without let_chains
, checking multiple patterns or conditions required nesting:
// Pre-Rust 2024: Nested structure
fn process_nested(opt_a: Option<i32>, opt_b: Option<&str>, flag: bool) {
if let Some(a) = opt_a {
if a > 10 {
if let Some(b) = opt_b {
if b.starts_with("prefix") {
if flag {
println!("All conditions met: a={}, b={}", a, b);
}
}
}
}
}
}
21.15.2 Example with if let
Chains
The equivalent code becomes much flatter and arguably more readable:
// Assumes Rust 2024 edition or later, or enabling the feature explicitly fn process_chained(opt_a: Option<i32>, opt_b: Option<&str>, flag: bool) { // Combine `if let` and boolean conditions with `&&` if let Some(a) = opt_a && a > 10 && let Some(b) = opt_b && b.starts_with("prefix") && flag { println!("All conditions met: a={}, b={}", a, b); } else { println!("Conditions not fully met."); } } fn main() { process_chained(Some(20), Some("prefix_data"), true); // Output: All conditions met... process_chained(Some(5), Some("prefix_data"), true); // Output: Conditions not fully met. (a > 10 fails) process_chained(Some(20), Some("other_data"), true); // Output: Conditions not fully met. (b.starts_with fails) process_chained(Some(20), Some("prefix_data"), false);// Output: Conditions not fully met. (flag fails) process_chained(None, Some("prefix_data"), true); // Output: Conditions not fully met. (opt_a is None) }
The conditions are evaluated left-to-right. If any let
pattern fails to match or any boolean expression is false, the entire if
condition short-circuits to false, and the else
block (if present) is executed.