if let is Rust syntax for handling one pattern without writing branches for every possible match. It runs the block when the value matches and otherwise continues without doing anything. For example, if let Some(number) = my_vec.get(index) extracts number only when get returns Some. section 5.2.3
fn main() {
let my_vec = vec![2, 3, 4];
for index in 0..10 {
if let Some(number) = my_vec.get(index) {
println!("The number is: {number}");
}
}
}
This example checks ten vector indexes but prints only the values found. The unmatched None results are ignored. section 5.2.3
The single equals sign matters: Some(number) = my_vec.get(index) performs pattern matching, not a boolean comparison. The name number exists only inside the if let block, where the match guarantees that it contains the extracted value. section 5.2.3
Reacting to selected events
An event loop can use if let Event::Key(key_event) = read().unwrap() to process keyboard events while ignoring mouse, resize, paste, and other event variants. A nested check then handles only pressed keys, such as characters, Backspace, or Escape. section 23.2.2
Use if let when one matching case matters and the other cases need no action. When the unmatched case must stop, continue, return, or otherwise diverge before later code, let else is the related alternative. section 5.2.3
