Rust Fundamentals · 20 XP Pro

if let and let-else

A full match is overkill when you only care about one pattern. if let runs a block when the value fits a pattern and skips it otherwise:

let maybe: Option<u32> = Some(7);

if let Some(n) = maybe {
    println!("got {n}");
} else {
    println!("nothing");
}

The else is optional. n exists only inside the block.

Sometimes the opposite is what you want: extract a value, and leave early if it isn't there, so the rest of the function stays un-nested. That is let ... else. The else block must diverge (return, break, continue or panic):

fn double_first(words: &[&str]) -> usize {
    let Some(w) = words.first() else {
        return 0;
    };
    w.len() * 2
}

After the statement, w is available in the normal scope.

Two helpers are useful here. s.split_once(',') returns Option<(&str, &str)>, splitting at the first comma. s.parse::<i32>().ok() turns a string into Option<i32>, giving None if it is not a number.

Your task

Everything must be pub.

  1. pub fn describe_age(age: Option<u32>) -> String: use if let. For Some(a) return "{a} years old", otherwise "age unknown".
  2. pub fn parse_pair(s: &str) -> Option<(i32, i32)>: parse text like "3,-4" into (3, -4). Use let ... else to return None when there is no comma or either side is not an integer. Trim whitespace around each side.
  3. pub fn last_word_len(text: &str) -> usize: length of the last whitespace-separated word, or 0 if there are none. Use text.split_whitespace().last() with let ... else.

Next lesson →

Sign in to run your code. It's free.