Sub topic 4
Adding else and else if let
This chapter assumes you know Option and Result, can read a basic match, and have seen plain if let from the previous chapter. It covers what happens when the pattern does not match, and how to chain several patterns in a row.
The else branch
A plain if let does nothing when the pattern fails. Adding else gives you a fallback. This is the same as a match with one interesting arm and a _ arm:
fn main() {
let count: Option<u32> = None;
let label = if let Some(n) = count {
format!("{n} items")
} else {
String::from("no items")
};
println!("{label}");
let label_match = match count {
Some(n) => format!("{n} items"),
_ => String::from("no items"),
};
println!("{label_match}");
}Both forms print no items. The if let ... else form is an expression, so you can assign its result to a variable. The binding n exists only inside the first block. The else block cannot see it, because the pattern did not match there.
Both branches must have the same type
Because the whole construct is an expression, every branch must produce the same type. This is the most common error when adding else:
fn main() {
let count: Option<u32> = Some(3);
// Does not compile: the first branch is a String, the second is ().
// let label = if let Some(n) = count {
// format!("{n} items")
// } else {
// println!("nothing");
// };
if let Some(n) = count {
println!("{n} items");
} else {
println!("nothing");
}
}If you only want side effects, make every branch evaluate to (), as the last if let above does. If you want a value, make every branch return one.
Chaining with else if let
You can place another if let after else. Rust tries each pattern in order and runs the first block that matches:
fn describe(input: &str) -> String {
if let Ok(n) = input.parse::<i32>() {
format!("integer {n}")
} else if let Ok(x) = input.parse::<f64>() {
format!("float {x}")
} else if input.is_empty() {
String::from("empty")
} else {
format!("text {input}")
}
}
fn main() {
for s in ["42", "3.5", "", "hi"] {
println!("{}", describe(s));
}
}The output is integer 42, float 3.5, empty, and text hi. Note three things:
- Each
if lethas its own bindings.nis not visible in thef64branch. - You can mix
else if letwith ordinaryelse ifconditions. - The order matters.
"42"would also parse as anf64, but thei32check runs first and wins.
No exhaustiveness checking
A match must cover every case, and the compiler enforces that. An if let chain does not. If you add a new variant to an enum, a match fails to compile until you handle it. An if let ... else if let ... chain keeps compiling and sends the new variant to the final else.
When the chain gets long
Two or three else if let links are readable. A longer chain usually means you are testing one value against many patterns, which is what match is for. If each link instead tests a different value, the nesting and repeated else are the problem that later chapters solve with let else and let chains.
Exercise
What does this code print, and why? fn main() { let value = "7"; let text = if let Ok(n) = value.parse::<u8>() { format!("small {n}") } else if let Ok(n) = value.parse::<i64>() { format!("big {n}") } else { String::from("neither") }; println!("{text}"); }
Show answer
It prints small 7. The u8 parse succeeds, so the first block runs and the later tests are never evaluated. The two n bindings are separate and never overlap.
Exercise
Why does let x = if let Some(n) = opt { n * 2 }; fail to compile when opt is an Option<i32>?
Show answer
Without an else, the expression has type () when the pattern does not match, but the matching branch has type i32. Add an else branch that also produces an i32, for example else { 0 }.