Sub topic 4
Adding else and else if let
This chapter assumes you know Option and Result, match with basic patterns, and the idea of refutable patterns from the earlier chapters. It also assumes you have seen a bare if let with no else. Here you will see how if let gets a fallback branch, how to chain several pattern tests, and where this style stops being the right tool.
From a bare if let to a full if let else
A bare if let handles one pattern and ignores everything else. That works when "nothing happens" is a fine result for the other cases. Often you need a fallback, and you add else:
fn describe_port(port: Option<u16>) -> String {
if let Some(p) = port {
format!("listening on {p}")
} else {
String::from("using default port 80")
}
}
fn main() {
println!("{}", describe_port(Some(8080)));
println!("{}", describe_port(None));
}The else block runs whenever the pattern does not match. It does not care why. For an Option<u16> there is only one other case, None. For a larger enum, else covers every remaining variant at once.
if let ... else is an expression, like if ... else. Both branches produce a value, and the whole construct evaluates to the value of whichever branch ran. That is why describe_port needs no return and no semicolon after the branches.
Both branches must have the same type
The compiler requires the if let block and the else block to evaluate to the same type. Two cases follow from this:
- With an
else, both branches may produce aString, ani32, or any other type, as long as the types agree. - Without an
else, the missing branch is treated as producing(). If yourif letblock produces anything other than(), the compiler reports a type mismatch and tells you that theifmay be missing anelseclause.
The second case is a common error. Adding a semicolon inside the block turns its value into () and silences the error, but then you have thrown the value away. If you meant to use the value, add the else branch.
fn main() {
let width: Option<u32> = Some(12);
let size = if let Some(w) = width { w } else { 0 };
println!("size = {size}");
}This particular example is the same as width.unwrap_or(0). When the fallback is a plain value, a method like unwrap_or is shorter. Use if let ... else when either branch does more than produce a value.
Where bindings are visible
A name bound in the pattern exists only in the if let block. The else block cannot see it, because in that branch the pattern did not match and the name has no value. This catches people who write if let Some(p) = port { ... } else { println!("{p}") }. The compiler reports p as an unresolved name.
If the else block needs the original value, keep it in a variable outside the construct. Match on a reference so the value is not moved:
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
if let Some(n) = &name {
println!("hello, {n}");
} else {
println!("hello, stranger");
}
println!("name is still usable: {name:?}");
}Matching on &name borrows the Option<String>, and n becomes a &String. Without the &, the String would move into n, and name would be partly moved after the block.
Chaining with else if let
An else can be followed by another if, as in any Rust conditional. It can also be followed by another if let. This gives you a ladder in which each rung tests a different pattern, and the rungs can be ordinary boolean tests too:
fn classify(input: &str) -> String {
if let Ok(n) = input.parse::<i64>() {
format!("integer {n}")
} else if let Ok(x) = input.parse::<f64>() {
format!("float {x}")
} else if input.is_empty() {
String::from("empty input")
} else {
format!("text {input:?}")
}
}
fn main() {
println!("{}", classify("42"));
println!("{}", classify("3.5"));
println!("{}", classify(""));
println!("{}", classify("abc"));
}This prints integer 42, float 3.5, empty input, and text "abc".
The rules for the ladder are:
- Conditions are tested from top to bottom, and the first one that succeeds runs its block. The rest are skipped.
- Each rung is independent. A binding from the first
if let(n) is not visible in the second rung's pattern or block. - The scrutinee of each rung (the expression after
=) is evaluated only if the earlier rungs failed. Inclassify, thef64parse never runs for"42". - Every block must produce the same type, and a final
elsemakes the whole chain an expression of that type.
Order matters when patterns overlap. The string "42" also parses as an f64, so the integer rung must come first if you want it classified as an integer.
No exhaustiveness check
match makes you handle every variant. if let ... else does not. The final else accepts everything that is left, including variants you have not written yet. Look at this code:
enum Command {
Quit,
Move { x: i32, y: i32 },
Say(String),
}
fn run(cmd: &Command) {
if let Command::Move { x, y } = cmd {
println!("moving by {x}, {y}");
} else if let Command::Say(text) = cmd {
println!("saying {text}");
} else {
println!("nothing to do");
}
}
fn main() {
run(&Command::Move { x: 1, y: -2 });
run(&Command::Say(String::from("hi")));
run(&Command::Quit);
}Suppose you later add Command::Jump. This code still compiles, and Jump silently falls into "nothing to do". A match on cmd with no wildcard arm would refuse to compile until you handled Jump. That compile error is often what you want.
The same function as a match:
enum Command {
Quit,
Move { x: i32, y: i32 },
Say(String),
}
fn run(cmd: &Command) {
match cmd {
Command::Move { x, y } => println!("moving by {x}, {y}"),
Command::Say(text) => println!("saying {text}"),
Command::Quit => println!("nothing to do"),
}
}
fn main() {
run(&Command::Move { x: 1, y: -2 });
run(&Command::Say(String::from("hi")));
run(&Command::Quit);
}if let else versus match
An if let ... else has the same behavior as a two-arm match, one arm for the pattern and a wildcard arm for the rest. The table shows how the forms compare.
| Form | Arms or branches | Exhaustiveness checked | Typical use |
|---|---|---|---|
| `if let P = e { A }` | one, plus an implicit `()` | no | run code for one pattern, ignore the rest |
| `if let P = e { A } else { B }` | two | no, `else` takes the rest | one pattern with a fallback |
| `if let ... else if let ... else` | three or more | no, final `else` takes the rest | a few unrelated tests, mixed with booleans |
| `match e { ... }` | any number | yes | one value, many shapes |
Three arms or rungs is the point where you should compare the two. If every rung tests the same value, a match is usually clearer and safer. A ladder is the better choice when the rungs test different values, as in classify where each rung parses the string a different way. It also fits when you need boolean conditions in between, which a match can only express with guards.
A scoping detail in edition 2021
In the 2021 edition, temporary values created in the scrutinee live until the end of the whole if let ... else statement. That includes the else block. A temporary is a value the compiler creates for an expression and does not store in a variable, such as a lock guard returned from mutex.lock().unwrap(). If such a guard is still alive inside the else block, code there that tries to lock the same mutex can deadlock. Edition 2024 changes this so temporaries are dropped before the else block runs. A later chapter covers this in detail.
Common mistakes
- Expecting the else block to see pattern bindings. It cannot. Use a reference to the original value instead.
- Mismatched branch types. If one branch produces
Stringand the other&str, the code does not compile. Convert one side, for example withString::from. - Overlapping patterns in the wrong order. The first rung that matches wins, so put the narrow tests above the broad ones.
- Long ladders. A ladder of five or six
else if letrungs on one enum is amatchin disguise, and it has lost the exhaustiveness check. - Nested ladders. When the
elseblocks themselves contain furtherif letstatements, the code drifts rightward. The next chapters on nesting and let chains address this.
Exercise
This function does not compile because of a type problem. Why, and what is the smallest change that fixes it? fn double(x: Option<i32>) -> i32 { if let Some(n) = x { n * 2 } }
Show answer
Without an else, the missing branch has type (), but the if let block produces an i32, so the two branches disagree. Add a fallback branch that produces an i32, for example else { 0 }. The function then returns 0 for None.
Exercise
A Command enum has the variants Quit, Move, and Say. A colleague writes an if let / else if let / else ladder over it, with the last else printing "nothing to do". Later someone adds a Jump variant. What happens at compile time, and which construct would behave differently?
Show answer
Nothing happens at compile time. The ladder still compiles, and Jump silently takes the else branch. A match over Command with no wildcard arm would fail to compile until Jump was handled, so it would flag the change.