🦀 Rust Beginner

What are if let and while let in Rust?

Answer

if let is syntactic sugar for a match that only handles one pattern, avoiding the verbosity of a full match when you only care about one case. Instead of match opt { Some(v) => do_something(v), _ => () }, you write if let Some(v) = opt { do_something(v) }. You can add an else branch for the non-matching case. while let loops as long as the pattern matches: while let Some(top) = stack.pop() { ... } — this is the idiomatic way to process a stack or iterator-like structure. Both constructs make code more readable when full exhaustive matching is unnecessary.