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.
Code
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
Resultvalues 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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.