Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

If let & let…else

If let

  • if let syntax can be used for instance for a match that runs code when the value matches one pattern and then ignores all other values.
  • if let takes a pattern and an expression from match separated by an equal sign
  • trade off between conciseness and exhaustive check
    // match version
    let config_max = Some(3u8);
    match config_max {
        Some(max) => println!("The maximum is configured to be {max}"),
        _ => (),
    }

    // if let syntax
    let config_max = Some(3u8);
    if let Some(max) = config_max {
        println!("The maximum is configured to be {max}");
    }

Let…else

  • Used when you expect a pattern to match otherwise you exit right away
fn print_length(name: Option<String>) {
    let Some(name) = name else {
        return;
    };

    println!("Length: {}", name.len());
}