Use if let to execute code only when an Option or Result matches a specific pattern, avoiding verbose match statements for single cases.
let some_option = Some(5);
if let Some(value) = some_option {
println!("The value is: {}", value);
}
For Result types, handle the success case similarly:
let result: Result<i32, &str> = Ok(42);
if let Ok(num) = result {
println!("Success: {}", num);
}
You can also add an else block to handle the non-matching case:
if let Some(x) = some_option {
println!("Got: {}", x);
} else {
println!("No value found");
}