Sub topic 3
if let: matching one pattern
This chapter assumes you know Option and Result, how match works, and the basics of ownership and borrowing. Here you will learn how if let replaces a match that cares about only one case.
From match to if let
Suppose you only want to act when an Option<u16> holds a value. A match needs a catch-all arm to be exhaustive, even though that arm does nothing:
fn main() {
let config_port: Option<u16> = Some(8080);
match config_port {
Some(port) => println!("listening on {port}"),
_ => {}
}
}if let expresses the same logic with less ceremony:
fn main() {
let config_port: Option<u16> = Some(8080);
if let Some(port) = config_port {
println!("listening on {port}");
}
}The syntax is if let PATTERN = EXPRESSION { ... }. Rust evaluates the expression on the right and tests it against the pattern on the left. If the pattern matches, the names it introduces, here port, are bound inside the block and the block runs. If it does not match, the block is skipped.
The equals sign is not comparison
In if let Some(port) = config_port, the = does not compare two values. It is the same destructuring = you use in let (a, b) = pair;. The pattern is on the left, and the value being tested is on the right. The difference from a plain let is that the pattern here is allowed to fail. The next chapter sections on refutability explain why that matters, but the short version is that a plain let demands a pattern that always matches, and if let does not.
Bindings are scoped to the block
The names a pattern introduces exist only inside the if let block. Using port after the closing brace is a compile error. This is deliberate. Outside the block, Rust cannot guarantee the pattern matched, so a binding there could have no value.
Moves and borrows
A pattern binds by moving or copying, just like a let. With Option<u16> this is invisible, because u16 is Copy. With a String inside, matching by value moves the string out:
fn main() {
let name: Option<String> = Some(String::from("Ada"));
if let Some(n) = &name {
println!("hello {n}");
}
println!("{name:?}");
}Matching on &name makes n a &String, so name is still usable afterwards. If you wrote if let Some(n) = name, the String would move into n, and the later println! would fail with a "borrow of partially moved value" error.
Common errors
- Using
==instead of a pattern.if config_port == Some(port)fails becauseportis not defined. Useif let Some(port) = config_port. - An irrefutable pattern.
if let x = 5 { ... }compiles, but the compiler warns that the pattern always matches. Plainletis the right tool there. - Expecting exhaustiveness checks.
matchmakes the compiler check that you covered every variant.if letdoes not, so if you later add a variant to your enum, the compiler will not point you to this spot.
When if let fits
Use if let when exactly one pattern deserves action and the rest should be ignored. If you need to treat several variants differently, a match is safer, since the compiler checks that every case is handled. Handling the non-matching case with an else branch is the subject of the next chapter.
Exercise
A function holds let reply: Result<u32, String> = Ok(7);. Write an if let that prints the number only when the result is Ok, and say what happens to the code inside the block if reply is Err.
Show answer
if let Ok(n) = reply { println!("got {n}"); }. If reply is Err, the pattern does not match, so the block is skipped and nothing is printed. The Err value is silently ignored, which is why match is safer when you must handle every case.