if let
- Rust course
- Beginner
- Lesson 85/115
- 4 min
Match a single pattern concisely with if let.
if let
If you only care about one pattern, if let is shorter than match; the other cases fall into else:
let ayar: Option<u32> = Some(8);
if let Some(n) = ayar {
println!("Seviye {n}");
} else {
println!("Varsayılan");
}The cost: you lose match's guarantee of checking every case. When there are several variants, prefer match.
let-else
To exit a function early when there is no value, let ... else is used; the else block must exit (return, break, continue or a panic):
fn ilk_harf(s: &str) -> char {
let Some(c) = s.chars().next() else {
return '?';
};
c.to_ascii_uppercase()
}
println!("{} {}", ilk_harf("rust"), ilk_harf("")); // R ?This way the happy path stays unindented.
Practice Read a setting
Declare let ayar: Option<u32> = Some(8); and let bos: Option<u32> = None;. For each, print Seviye N with if let Some(n), otherwise Varsayılan.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let ayar: Option<u32> = Some(8);
let bos: Option<u32> = None;
for a in [ayar, bos] {
if let Some(n) = a {
println!("Seviye {}", n);
} else {
println!("Varsayılan");
}
}
}Expected output
Seviye 8 Varsayılan
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which <code>match</code> is <code>if let Some(n) = x</code> equivalent to?
- match x { None => { .. } }
- match n { Some(x) => .. }
- It has no equivalent
- match x { Some(n) => { .. }, _ => {} } Correct answer
Explanation: if let is shorthand for a match with one arm that ignores the rest.
2 A single pattern
____ Some(n) = ayar {
println!("Seviye {n}");
}
if let Some(n) = ayar {
println!("Seviye {n}");
}
Explanation: if let runs the block if a single pattern fits.
3 Construct and where to use it
| Term | Meaning |
|---|---|
match |
All cases |
if let |
A single pattern |
let-else |
Early exit |
matches! |
bool result |