liveBook · Manning

If let

As explained in Learn Rust in a Month of Lunches

if let is Rust conditional pattern-matching syntax that executes a block when a value matches a specified pattern and otherwise continues without executing that block.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines syntax, equality notation, block scope, and practical use, then contrasts it briefly with let else.
Examples
Uses vector lookups, repeated index checks, parsed integers, and keyboard events from a terminal typing program.
What it assumes
Assumes familiarity with match, Option, Result, vectors, and enum variants while reinforcing safe matching through examples.
What you can do after
Apply pattern matching to handle selected Option, Result, or enum variants without writing unnecessary fallback branches.
How it connects
Connects pattern matching with Option, Result, match, vector indexing, event handling, and let else.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.