If Let And While Let Ergonomics

Unwrap single-pattern Options and Results with if let and drain queues with while let, keeping the happy path at full indent depth.

RustData Integrity

Code

rustsnippet
20 lines
fn main() {
    let maybe: Option<&str> = Some("value");
    // if let:只关心一个形态时替代完整 match
    if let Some(inner) = maybe {
        println!("got: {}", inner);
    }

    let mut queue = vec![Some(1), None, Some(3)];
    // while let:逐个弹出直到 None
    while let Some(item) = queue.pop() {
        if let Some(n) = item {
            println!("popped: {}", n);
        }
    }

    let result: Result<i32, &str> = Ok(7);
    if let Ok(v) = result {
        println!("ok value: {}", v);
    }
}

What the code does

If Let And While Let Ergonomics is built around the function main.

Repetition is confined to while let Some(item) = queue.pop() — the rest of the file is straight-line. Result turns the error into data — visible in the type, handled by the caller.

What to watch for

  • The Result values will not let errors pass silently; each must be matched, unwrapped, or propagated.

Applying it

Running the file prints labeled results such as got:, popped:, ok value: — each operation’s effect is visible in the output.

Statements that matter

let mut queue = vec![Some(1), None, Some(3)];
while let Some(item) = queue.pop() {
    if let Some(n) = item {
        println!("popped: {}", n);
    }
}
let maybe: Option<&str> = Some("value");

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does If Let And While Let Ergonomics print when run?
Running the file directly is enough — expect labeled output lines such as `got:`, `popped:`, `ok value:`.