Rust

if let / while let

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When you only care about one variant, `if let` is shorter than `match`. `while let` keeps looping as long as the pattern matches — great for draining iterators or option-returning APIs.
Rust
Raw
fn main() {
    let some_value = Some(42);

    // Instead of full match:
    if let Some(n) = some_value {
        println!("got {n}");
    } else {
        println!("nothing");
    }

    // Drain a stack until empty
    let mut stack = vec![1, 2, 3, 4, 5];
    while let Some(top) = stack.pop() {
        println!("popped {top}");
    }

    // Combined with let-else (Rust 1.65+) for early-return shape
    fn parse_id(s: &str) -> Result<u64, String> {
        let Ok(n) = s.parse::<u64>() else {
            return Err(format!("not a number: {s}"));
        };
        Ok(n + 1)
    }
    println!("{:?}", parse_id("9"));            // Ok(10)
    println!("{:?}", parse_id("xyz"));          // Err("not a number: xyz")
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.