Module 4 · Control flow & pattern matching
4.3if let, while let & let-else
The short forms of match that check one pattern, how they map to the checks you already write for missing values, and when to use each one.
On this page
- Concept map
- A value or nothing: Some and None
- if let: check one pattern
- Extra conditions: let chains
- let ... else: unwrap or leave early
- while let: loop while it matches
- Which one should I use?
- Under the hood
- They’re all match
- Refutable and irrefutable patterns
- Why the else must leave
- Common pitfalls
- Try it yourself
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| A value that may be missing | T | undefined | T? | Option<T>: Some(value) or None |
| Check and use it in one step | if (x !== undefined) narrows x | if (x is string s) | if let Some(s) = x |
| Leave early if it's missing | if (x === undefined) return; | if (x is not string s) return; | let Some(s) = x else { return; }; |
| Loop while there's a next value | while ((x = stack.pop()) !== undefined) | while (stack.TryPop(out var x)) | while let Some(x) = stack.pop() |
| Use a default instead | x ?? fallback | x ?? fallback | x.unwrap_or(fallback) |
A full match is the right tool when every case matters. Often only one does: “if there’s a first item, greet it”, “if this line has an =, split it”, “keep popping while the stack has something”. TypeScript handles these with narrowing.C# handles these with is patterns. Rust has three short forms of match for them: if let, let ... else and while let.
A value or nothing: Some and None
Most examples here use Option, so here’s just enough of it. Rust has no null or undefined. A function that might not have a value to return gives you an Option<T>, an enum with two variants:
Some(value): there is a value, wrapped inside.None: there isn’t.
It plays the role of T | undefined in TypeScriptT? in C#. The difference is that you can’t use the value until you’ve checked which variant you have; the compiler won’t let you forget. names.first(), stack.pop() and text.split_once('=') all return an Option. Module 6 covers Option in full.
if let: check one pattern
if let PATTERN = VALUE { ... } runs the block only when the value matches the pattern, and binds the names in it. It does the job of TypeScript narrowingC#‘s is pattern:
function greetFirst(names: string[]): void {
const first = names[0];
if (first !== undefined) {
console.log(`hello ${first}`);
} else {
console.log("nobody to greet");
}
}
greetFirst(["Ada", "Grace"]);
greetFirst([]);GreetFirst(["Ada", "Grace"]);
GreetFirst([]);
static void GreetFirst(List<string> names)
{
if (names.FirstOrDefault() is string first)
{
Console.WriteLine($"hello {first}");
}
else
{
Console.WriteLine("nobody to greet");
}
}fn greet_first(names: &[&str]) {
if let Some(first) = names.first() {
println!("hello {first}");
} else {
println!("nobody to greet");
}
}
fn main() {
greet_first(&["Ada", "Grace"]);
greet_first(&[]);
}Output
hello Ada nobody to greet
Read if let Some(first) = names.first() as “if names.first() is a Some, call what’s inside first”. The = here is not a comparison and not an assignment: it means “match against”. first exists only inside the block, where it’s guaranteed to be there. In the else block, there’s nothing to bind.
if let works with any pattern, not just Option: if let Command::Move { x, y } = command, or if let (0, y) = point. It’s a match with one interesting arm.
Extra conditions: let chains
In the 2024 edition (Rust 1.88 and later), you can join let patterns and ordinary conditions with &&, like TypeScript’s if (first !== undefined && first.length > 3)C#‘s if (names.FirstOrDefault() is string first && first.Length > 3):
let names = ["Grace", "Ada"];
if let Some(first) = names.first()
&& first.len() > 3
{
println!("{first} has a long name");
}Each part can use the names bound before it, and the block runs only if every part succeeds.
let ... else: unwrap or leave early
A guard clause checks for the bad case at the top of a function and returns, so the rest of the code can assume the good case. TypeScript narrowing supports this.C#‘s is not pattern supports this: the names it binds stay in scope after the early return. Rust’s version is let PATTERN = VALUE else { ... };:
function printSetting(line: string): void {
const at = line.indexOf("=");
if (at === -1) {
console.log(`skipped: ${line}`);
return;
}
const key = line.slice(0, at);
const value = line.slice(at + 1);
console.log(`${key} -> ${value}`);
}
printSetting("port=8080");
printSetting("debug");
printSetting("host=localhost");PrintSetting("port=8080");
PrintSetting("debug");
PrintSetting("host=localhost");
static void PrintSetting(string line)
{
if (line.Split('=', 2) is not [var key, var value])
{
Console.WriteLine($"skipped: {line}");
return;
}
Console.WriteLine($"{key} -> {value}");
}fn print_setting(line: &str) {
let Some((key, value)) = line.split_once('=') else {
println!("skipped: {line}");
return;
};
println!("{key} -> {value}");
}
fn main() {
print_setting("port=8080");
print_setting("debug");
print_setting("host=localhost");
}Output
port -> 8080 skipped: debug host -> localhost
split_once('=') returns Some((key, value)) or None. The pattern takes the Some and the tuple inside apart in one go. If it doesn’t match, the else block runs, and that block must not continue: it has to return, break, continue or panic. In exchange, key and value are ordinary variables for the rest of the function, with no extra nesting.
Mental model shiftThe happy path stays flat
With if let, the code that uses the value is nested inside the block. With let ... else, it isn’t: the failure case leaves, and everything after the let reads top to bottom. Reach for it wherever you’d write a guard clause in TypeScriptC#.
while let: loop while it matches
while let PATTERN = VALUE { ... } checks the pattern before every pass and stops the first time it fails. Popping a stack until it’s empty is the classic case:
const undo = ["type a", "type b", "delete"];
let action: string | undefined;
while ((action = undo.pop()) !== undefined) {
console.log(`undo ${action}`);
}var undo = new Stack<string>(new[] { "type a", "type b", "delete" });
while (undo.TryPop(out var action))
{
Console.WriteLine($"undo {action}");
}let mut undo = vec!["type a", "type b", "delete"];
while let Some(action) = undo.pop() {
println!("undo {action}");
}Output
undo delete undo type b undo type a
undo.pop() returns Some(last item) and removes it, or None once the vector is empty. There’s no separate variable declared outside the loop, and no assignment hidden inside a condition.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
match | Two or more cases each need their own code. | Exhaustive: the compiler checks you handled every case. | match value { Some(x) => ..., None => ... } |
if let | You care about one pattern; the rest is “do nothing” or one else. | Shorter than a match with an empty _ => {} arm. | if let Some(x) = value { ... } else { ... } |
let ... else | The value must be there for the rest of the function or loop body; otherwise leave. | Keeps the main path flat, and the names stay in scope after the check. | let Some(x) = value else { return; }; |
while let | Repeat while something produces a matching value: popping a stack, reading a queue. | Combines “get next”, “check” and “bind” in the loop header. | while let Some(x) = stack.pop() { ... } |
unwrap_or | A missing value has a sensible default. | One expression, no branch at all. | let port = maybe_port.unwrap_or(8080); Module 6 covers this and its relatives. |
Rule of thumb: if you’d write a guard clause, use let ... else. If only one case does anything, use if let. If both cases do real work, use match. If there’s a default, use unwrap_or. Use while let for “pop until empty”, but loop over an iterator with for.
With matches! from Exhaustive match & destructuring added, the whole family fits one set of questions, asked in order:
Do you repeat while something keeps producing a value, like
stack.pop()?YesNowhile let Some(x) = stack.pop()For a plain iterator, write aforloop instead.Do you only need a
bool: does the value fit the pattern or not?YesNomatches!(value, pattern)Is there a sensible default when the value is missing?
YesNovalue.unwrap_or(default)One expression, no branch.Must the value be there for the rest of the function or loop body, and otherwise you leave?
YesNolet Some(x) = value else { return; };The guard clause: the main path stays flat.Does only one case do anything, with nothing or one
elsefor the rest?YesNoif let Some(x) = value { ... }Otherwise:
match: two or more cases each need their own code, and the compiler checks you handled them all
Under the hood
They’re all match
None of these is new machinery. The compiler treats each one as a match with a fixed second arm:
| You write | It means |
|---|---|
if let P = v { A } else { B } | match v { P => A, _ => B } |
while let P = v { A } | loop { match v { P => A, _ => break } } |
let P = v else { B }; | match v { P => bind the names, _ => B }, where B must leave |
So greet_first above is exactly this match:
let names = ["Ada", "Grace"];
match names.first() {
Some(first) => println!("hello {first}"),
None => println!("nobody to greet"),
}Refutable and irrefutable patterns
A pattern that can fail to match, like Some(first), is refutable. A pattern that always matches, like (x, y) against a pair or a plain name, is irrefutable. Plain let and function parameters accept only irrefutable patterns, because there’s nowhere to go if the match fails:
let names = ["Ada", "Grace"];
let Some(first) = names.first();
println!("{first}");Rust doesn't compile this: error E0005
error[E0005]: refutable pattern in local binding
--> main.rs:2:5
|
2 | let Some(first) = names.first();
| ^^^^^^^^^^^ pattern `None` not covered
|
= note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
= note: for more information, visit https://doc.rust-lang.org/book/ch19-02-refutability.html
= note: the matched value is of type `Option<&&str>`
help: you might want to use `let else` to handle the variant that isn't matched
|
2 | let Some(first) = names.first() else { todo!() };
| ++++++++++++++++That’s exactly the gap let ... else fills: it gives the failed match somewhere to go. The opposite mistake, if let with a pattern that can’t fail, compiles with a warning, because the if is pointless.
Why the else must leave
After a let ... else, the code uses first as if it exists. If the else block could just finish and fall through, first would be unset. So the compiler requires the block to diverge: its type must be !, the “never returns” type that return, break, continue and panic! have.
let names = ["Ada"];
let Some(first) = names.first() else {
println!("nobody to greet");
};
println!("hello {first}");Rust doesn't compile this: error E0308
error[E0308]: `else` clause of `let...else` does not diverge
--> main.rs:2:38
|
2 | let Some(first) = names.first() else {
| __________________________________________^
3 | | println!("nobody to greet");
4 | | };
| |_____^ expected `!`, found `()`
|
= note: expected type `!`
found unit type `()`
= help: try adding a diverging expression, such as `return` or `panic!(..)`
= help: ...or use `match` instead of `let...else`Common pitfalls
Common pitfallif let moves the value out
TypeScript narrowing never changes the variable.In C#, x is string s gives you a second reference and leaves x usable. In Rust, if let Some(name) = nickname matches the Option by value, so a String inside is moved into name, and nickname can’t be used afterwards:
let nickname: Option<String> = Some(String::from("Ace"));
if let Some(name) = nickname {
println!("hi {name}");
}
println!("{nickname:?}");Rust doesn't compile this: error E0382
error[E0382]: borrow of partially moved value: `nickname`
--> main.rs:5:12
|
2 | if let Some(name) = nickname {
| ---- value partially moved here
...
5 | println!("{nickname:?}");
| ^^^^^^^^ value borrowed here after partial move
|
= note: partial move occurs because value has type `String`, which does not implement the `Copy` trait
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: borrow this binding in the pattern to avoid moving the value
|
2 | if let Some(ref name) = nickname {
| +++Line by line, the String leaves nickname on line 2:
| Line | Code | nicknameowner | nameowner | nicknamemoved out | What happens |
|---|---|---|---|---|---|
| 1 | let nickname: Option<String> = Some(String::from("Ace")); | ownsnickname starts | |||
| 2 | if let Some(name) = nickname { | nickname ends | ownsname starts | The String inside nickname moves into name. | |
| 3 | println!("hi {name}"); | name alive | movednickname starts | ||
| 4 | } | name ends | nickname alive | The block ends and drops name's String. | |
| 5 | println!("{nickname:?}"); | nickname ends | errornickname was partly moved on line 2 (E0382). |
Five lines. nickname owns Some of the String Ace on lines 1 and 2. The if let on line 2 matches by value, so the String inside moves into name, which owns it until the block ends on line 4 and then drops it. From line 3 on, nickname is moved out, so printing it on line 5 is a compile error.
Match on a borrow, if let Some(name) = &nickname, and name becomes a &String while nickname stays intact. The same goes for let ... else and match.
Common pitfallA chain of if let ... else if let is a match
if let Some(x) = a { ... } else if let Some(y) = b { ... } else { ... } is fine for two unrelated values. When every branch tests the same value against a different pattern, write a match instead: it’s shorter, and the compiler checks you covered every case. if let never checks exhaustiveness.
Common pitfallDon't write while let over an iterator
while let Some(name) = iter.next() works, but it’s a hand-written for loop, and Clippy flags it. Write for name in iter. Keep while let for things that aren’t plain iteration, like stack.pop(), where the loop body may push new items.
Idiomatic RustDon't reach for unwrap() to skip the check
names.first().unwrap() compiles and gives you the value, but it panics (crashes the thread) on None, like a TypeError from reading undefinedNullReferenceException you chose to risk. Use let ... else with a clear message or a return, or unwrap_or with a default. Module 6 explains when unwrap and expect are acceptable.
Try it yourself
Exercise: port this to Rust
Port this task runner to Rust. Pop tasks from the end of the list until it’s empty. Each task should look like name:minutes; skip any task without a colon.
const tasks = ["write:30", "review", "ship:5"];
let task: string | undefined;
while ((task = tasks.pop()) !== undefined) {
const at = task.indexOf(":");
if (at === -1) {
console.log(`skipped ${task}`);
continue;
}
console.log(`${task.slice(0, at)} takes ${task.slice(at + 1)} min`);
}var tasks = new Stack<string>(new[] { "write:30", "review", "ship:5" });
while (tasks.TryPop(out var task))
{
if (task.Split(':', 2) is not [var name, var minutes])
{
Console.WriteLine($"skipped {task}");
continue;
}
Console.WriteLine($"{name} takes {minutes} min");
}Expected output
ship takes 5 min skipped review write takes 30 min
Show a hint
Use while let Some(task) = tasks.pop() for the loop. Inside it, write let Some((name, minutes)) = task.split_once(':') else { ... continue; }; to skip tasks without a colon.
Show a solution
let mut tasks = vec!["write:30", "review", "ship:5"];
while let Some(task) = tasks.pop() {
let Some((name, minutes)) = task.split_once(':') else {
println!("skipped {task}");
continue;
};
println!("{name} takes {minutes} min");
}while let pops until the vector is empty, so no counter or empty check is needed. let-else turns the colon check into a guard clause: tasks without one print a message and continue, and name and minutes are plain variables for the rest of the loop body.
Saved in this browser only.