Sub topic 3
if let: matching one pattern
This chapter assumes you know basic Rust syntax, the Option and Result enums, match with simple patterns, and the basics of ownership and borrowing. It covers the plain form of if let: what it expands to, how bindings and moves behave, and the mistakes people make with it. Adding else branches comes in the next chapter.
The problem: a match with one interesting arm
Suppose you only care about the Some case of an Option. A match must be exhaustive, so you write a catch-all arm that does nothing:
fn main() {
let config_port: Option<u16> = Some(8080);
match config_port {
Some(port) => println!("listening on {port}"),
_ => {}
}
}The _ => {} arm is noise. It also makes the reader check that the arm really is empty. if let removes it.
The if let form
The syntax is if let PATTERN = EXPRESSION { BLOCK }. The expression on the right is evaluated once. If its value matches the pattern, the names the pattern introduces are bound and the block runs. If it doesn't match, the block is skipped.
fn main() {
let config_port: Option<u16> = Some(8080);
if let Some(port) = config_port {
println!("listening on {port}");
} else {
println!("using default port");
}
}Note the single =. This is not a comparison. It is the same pattern-on-the-left, value-on-the-right shape as an ordinary let, except that the pattern is allowed to fail.
What if let really is
if let is sugar for a two-arm match. These two pieces of code mean the same thing:
fn main() {
let value: Option<i32> = Some(3);
if let Some(n) = value {
println!("got {n}");
}
match value {
Some(n) => println!("got {n}"),
_ => (),
}
}Two consequences follow from that.
- Without
else, the block must have type(). The skipped case produces(), so the matched case must too. A block that ends in a value such asn + 1without anelseis a type error. - The value is computed once. If the expression is a function call, it runs a single time, whether or not the pattern matches.
Which patterns you can use
Any refutable pattern works. A refutable pattern is one that can fail to match, which the previous chapter covered. The common ones are enum variants with data, struct patterns, literals, and ranges.
enum Command {
Quit,
Move { x: i32, y: i32 },
Say(String),
}
fn main() {
let commands = vec![
Command::Say(String::from("hello")),
Command::Move { x: 3, y: -1 },
Command::Quit,
];
for command in &commands {
if let Command::Move { x, y } = command {
println!("move by {x}, {y}");
}
if let Command::Say(text) = command {
println!("say {text}");
}
}
}Each if let tests one variant and ignores the rest. Quit matches neither, so nothing happens for it.
Literals and ranges can sit inside the pattern. The @ operator binds the matched value to a name while also testing it:
fn main() {
let readings = [Some(7), None, Some(42), Some(100)];
for reading in readings {
if let Some(n @ 0..=50) = reading {
println!("in range: {n}");
}
}
}This prints in range: 7 and in range: 42. The None and the Some(100) fail the pattern and are skipped.
Bindings are scoped to the block
Names introduced by the pattern exist only inside the if let block. After the closing brace, port or n no longer exists. If you need the unwrapped value for the rest of the function, if let is the wrong tool. let else, covered later in this tutorial, is built for that.
A pattern binding can also shadow an outer name:
fn main() {
let port: Option<u16> = Some(8080);
if let Some(port) = port {
println!("inside: {port}");
}
println!("outside: {port:?}");
}Inside the block, port is a u16. Outside, it is still the Option<u16>. Shadowing is legal and common, but giving the inner name a different name often reads better.
Moves and borrows in patterns
A binding in a pattern follows the usual ownership rules. If the matched value is not Copy, binding by value moves it.
fn main() {
let nickname: Option<String> = Some(String::from("ferris"));
if let Some(name) = &nickname {
println!("hello, {name}");
}
println!("still available: {nickname:?}");
}Matching on &nickname makes name a &String, so nickname stays intact. Remove the & and the String moves into name. The later println! then fails with error E0382, "borrow of partially moved value". The move happens even when the pattern doesn't match in a way that visibly consumes anything, because the compiler reasons about the possible path.
To change the value in place, match on a mutable reference:
fn main() {
let mut retries: Option<u32> = Some(2);
if let Some(count) = &mut retries {
*count += 1;
}
println!("{retries:?}");
}This prints Some(3). Here count is a &mut u32, so you assign through it with *.
Common errors
Using an irrefutable pattern. A pattern that can never fail makes the if pointless. if let x = 5 { ... } compiles, but the compiler warns about an irrefutable if let pattern. The warning usually means you meant a refutable pattern, or that a plain let is enough.
Writing == instead of =. if let Some(x) == opt is a syntax error. The pattern is not an expression, so it can't be compared.
Expecting a lowercase name to compare. In a pattern, a lowercase identifier creates a new binding. It does not compare against an existing variable of that name.
fn main() {
let expected = 10;
let actual = Some(3);
if let Some(expected) = actual {
println!("this always runs for Some, and expected is now {expected}");
}
}This prints this always runs for Some, and expected is now 3. The pattern doesn't check that actual holds 10. To compare against a fixed value, use a literal (Some(10)) or a const (Some(LIMIT)), or add a condition. Conditions get easier to write once you reach let chains.
Using if let for a yes/no test. If you don't need the bound values, matches! is shorter. matches!(value, Some(_)) returns a bool and can be used directly in other conditions.
Losing exhaustiveness checking. A match on an enum fails to compile when you add a variant and forget to handle it. An if let silently ignores the new variant. This is the main trade-off. Use if let when ignoring the other cases is truly intended, and use match when a new variant should force you to revisit the code.
Summary of behavior
| Property | `if let` |
|---|---|
| Pattern kind | Refutable (an irrefutable one triggers a warning) |
| Exhaustiveness checked | No |
| Names bound | Only inside the block |
| Type without `else` | The block must be `()` |
| Moves non-`Copy` values | Yes, unless you match on a reference |
Exercise
Given let mut name: Option<String> = Some(String::from("ada"));, write an if let that appends "!" to the string inside the Option without moving it out, then print name with {name:?}. What does it print?
Show answer
Match on a mutable reference so s is a &mut String:
if let Some(s) = &mut name {
s.push('!');
}
println!("{name:?}");
It prints Some("ada!"). Matching on &mut name borrows the string instead of moving it, so name is still usable afterwards.
Exercise
Why does if let Some(limit) = reading { ... } not check whether reading equals an existing variable called limit, and how would you test against a fixed value 10 instead?
Show answer
A lowercase identifier in a pattern creates a new binding that shadows any outer limit. It never compares. To test for 10, write the literal in the pattern, as in if let Some(10) = reading, or use a const name in uppercase.