if let Syntax
if let is a shortcut for handling just one interesting case of a value, without writing out every possibility.Basic if let
if let matches a value against a single pattern and runs its block only if that pattern matches, skipping the block entirely otherwise. It's a shorthand for a match that only cares about one case.
Example: Basic if let
fn main() {
let config_max: Option<u8> = Some(3);
if let Some(max) = config_max {
println!("Maximum is configured to be {}", max);
}
}
Login to try C/C++/Java/PHP code in the editor
if let With else
Adding an else block to if let lets you handle the non-matching case as well, giving you full coverage with less boilerplate than a match when there is only one interesting variant.
Example: if let With else
fn main() {
let value: Option<i32> = None;
if let Some(v) = value {
println!("Got value: {}", v);
} else {
println!("No value present");
}
}
Login to try C/C++/Java/PHP code in the editor
if let With an Enum
if let works with any enum, not just Option, letting you handle a single variant of interest concisely while ignoring the rest.
Example: if let With an Enum
enum Shape {
Circle(f64),
Square(f64),
}
fn main() {
let shape = Shape::Circle(3.0);
if let Shape::Circle(radius) = shape {
println!("Circle with radius {}", radius);
}
}
Login to try C/C++/Java/PHP code in the editor
Choosing if let vs match
if let is best when you only care about one specific pattern and want to ignore everything else concisely; match is better when you need to handle every possible case explicitly.
Example: Choosing if let vs match
fn main() {
let items = [Some(1), None, Some(3)];
for item in items.iter() {
if let Some(n) = item {
println!("Found: {}", n);
}
}
}
Login to try C/C++/Java/PHP code in the editor
- Using a full
matchwith a wildcard_ => {}arm when a much shorterif letwould express the same logic. - Forgetting
if letis non-exhaustive by design -- it deliberately ignores every case that doesn't match the given pattern. - Not realizing
if let ... elsecan handle the non-matching case too, combining the concise syntax with full coverage.
if let pattern = value { ... }runs the block only whenvaluematches the given pattern.if letis useful when only one variant of amatchactually matters, avoiding boilerplate for the rest.- An
elsebranch can be attached toif letto handle every other case in one place. - Unlike
match,if letdoes not need to be exhaustive.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: