The Analogy: The Signal Box
At a railway junction the tracks split, and a set of points decides which way a train goes. The points are not advice. They are a physical object with exactly two positions, and whichever way they are set is where the train ends up. There is no third option and no "probably left". A train that arrives at points nobody has set does not choose for itself; the signal protecting that junction stays at danger and the train stops.
Behind the junction sits the signal box, and inside it the interlocking: a mechanism that refuses to let the signaller set a route that does not add up. You cannot clear a signal onto a line that has no exit. You cannot set two conflicting routes at once. The interlocking is not there because signallers are careless. It is there because a junction with an unaccounted-for route is a junction that will eventually put a train somewhere nobody planned.
Rust's if is the points, and match is the interlocking. if takes a bool -- not a number, not a pointer, not "something non-empty" -- and sends control down exactly one of two tracks. If you use it as an expression, both tracks have to arrive at the same platform, which is why if c { 1 } else { "one" } is a type error rather than a surprise at run time. match goes further: it enumerates the routes, and the compiler checks that every possible value of the subject has one. Leave a case out and you get error[E0004]: non-exhaustive patterns, before the program has ever run.
The consequence is that control flow in Rust is mostly about producing an answer, not about jumping around. if, match, and blocks are all expressions, so the natural shape is let decision = match status { ... }; -- one binding, one place the value comes from, and a compiler guarantee that no path forgot to set it. Once the exhaustiveness check is working for you rather than against you, adding a variant to an enum becomes a build error at every place that needs updating, which is the single most useful refactoring tool the language has.
Syntax or Core Structure
Every branching form in one program. Read the comments -- each one marks a rule that differs from C, Java, or Python.
fn main() {
let n = 7;
// The condition must be a `bool`. There is no truthiness, and the
// parentheses that C requires are not wanted here.
if n % 2 == 0 {
println!("{n} is even");
} else if n % 3 == 0 {
println!("{n} is divisible by three");
} else {
println!("{n} is neither");
}
// `if` is an expression, so both arms must produce the same type.
let size = if n < 10 { "small" } else { "large" };
println!("size = {size}");
// `match` tries patterns top to bottom and must cover every value.
let hint = match n {
0 => "zero",
1 | 2 | 3 => "tiny",
4..=9 => "single digit",
_ => "big",
};
println!("hint = {hint}");
// `@` binds the matched value; a guard adds a condition to one arm.
let http = 404;
let text = match http {
code @ 200..=299 => format!("ok ({code})"),
301 | 302 => "redirect".to_string(),
code if code >= 500 => format!("server error ({code})"),
code => format!("client error ({code})"),
};
println!("text = {text}");
// `if let` runs a block only when one pattern matches.
let maybe: Option<i32> = Some(3);
if let Some(v) = maybe {
println!("got {v}");
}
}
Output:
7 is neither
size = small
hint = single digit
text = client error (404)
got 3
Two of those rules are worth seeing fail. First, the condition really must be a bool -- an integer is not "true when non-zero":
fn main() {
let n = 7;
if n {
println!("truthy?");
}
}
Output (compile error, trimmed):
error[E0308]: mismatched types
--> src/main.rs:3:8
|
3 | if n {
| ^ expected `bool`, found `i32`
Second, a match that leaves a value unaccounted for is rejected outright. Here bool has exactly two values and only one has an arm:
fn main() {
let flag = true;
let s = match flag {
true => "yes",
};
println!("{s}");
}
Output (compile error, trimmed):
error[E0004]: non-exhaustive patterns: `false` not covered
--> src/main.rs:3:19
|
3 | let s = match flag {
| ^^^^ pattern `false` not covered
|
help: ensure the match is exhaustive by adding a match arm with a pattern
That second error is the whole point of match. The compiler is not asking you to be tidy; it is refusing to let a value fall through a junction with no route set.
Technical Depth: Patterns, Guards, and Exhaustiveness
How Rust's if differs from the one you already know
| Detail | Rust's rule | Why it matters |
|---|---|---|
| Condition type | Must be exactly bool | if ptr, if count, and if list are all compile errors, so "I meant != 0" bugs cannot happen |
| Parentheses | Not required; rustc's unused_parens lint warns if you add them | if (a) && (b) is legal but linted -- the idiom is bare |
| Braces | Always required, even for one statement | The dangling-else and "added a second line to the body" bug classes do not exist |
| Assignment in a condition | if x = 5 produces expected bool, found () | The classic = for == typo is a compile error, not a silent truth |
| Value | It is an expression; the arms must agree on type | let x = if c { 1 } else { 2 }; replaces the uninitialised-then-assigned dance |
Missing else | Then the if must evaluate to () | let x = if c { 1 }; is an error -- there is no implicit default |
The patterns you can write in an arm
| Pattern | Matches |
|---|---|
404 | that exact literal |
'a'..='z' | an inclusive range of char |
0..10 | an exclusive range, stable in patterns since Rust 1.80 |
200..=299 | an inclusive numeric range |
code @ 500..=599 | the range, and binds the value to code |
_ | anything, binding nothing |
other | anything, binding it to other |
Some(v) | the Some variant, binding its payload to v |
| an or-pattern | any of several patterns, joined by the vertical-bar operator |
(a, b) | a tuple, destructured into two bindings |
Two things about ranges catch people out. ..= is inclusive and .. is exclusive, exactly as in the range expressions from the loops lesson -- so 0..10 covers nine and stops. And ranges in patterns only work on integers, char, and floats; you cannot range-match a &str.
Guards do not count towards exhaustiveness
This is the single most surprising rule in the whole feature, and it is deliberate:
fn sign(n: i32) -> &'static str {
match n {
x if x > 0 => "positive",
x if x <= 0 => "non-positive",
}
}
A human can see those two arms cover every i32. The compiler cannot, because a guard is arbitrary code that it does not evaluate, so it reports error[E0004]: non-exhaustive patterns: i32::MIN..=i32::MAX not covered. The fix is to make the last arm a pattern with no guard -- _ => "non-positive" -- which is also more honest, since it says "everything else" instead of restating a condition the reader has to check against the first one.
Order matters, and rustc tells you when it stops mattering
Arms are tried top to bottom, so a broad pattern above a narrow one swallows it. Rust catches that with the unreachable_pattern warning:
warning: unreachable pattern
--> src/main.rs:5:9
|
5 | 404 => "not found",
| ^^^ no value can reach this
That warning fires whenever a _ (or any catch-all binding) sits above a specific arm. Treat it as an error in review: it always means an arm you wrote is dead.
The three shorthand forms
Full match is not always what you want. Rust has three narrower tools:
| Form | Shape | Use it when |
|---|---|---|
if let | if let Some(v) = opt { ... } else { ... } | Exactly one pattern is interesting and the rest do nothing |
let ... else | let Some(v) = opt else { return; }; | Bind or bail -- the else block must diverge |
matches! | matches!(v, 'a'..='z') | You only want a bool answer, not a branch |
let ... else (stable since Rust 1.65) is the one that changes how code looks. Its else block is required to diverge -- return, break, continue, or panic! -- which means the binding it introduces is available for the rest of the function at the outer indentation level, instead of nesting one level deeper for every check. A function with four preconditions stays flat.
Rust 1.88 on the 2024 edition added let chains, so if let Some(a) = x && let Some(b) = y && b > a { ... } is a single condition rather than three nested blocks. If you are on an older toolchain or an older edition, the equivalent is a match on the tuple (x, y).
Here are all three, plus guards, in one runnable program:
fn tier(score: i32) -> &'static str {
match score {
s if s < 0 => "invalid",
0 => "unranked",
1..=49 => "bronze",
50..=79 => "silver",
_ => "gold",
}
}
fn parse_flag(raw: &str) -> bool {
matches!(raw.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
}
fn first_word(line: &str) -> &str {
let Some(word) = line.split_whitespace().next() else {
return "<empty>";
};
word
}
fn main() {
for s in [-5, 0, 30, 65, 100] {
println!("{s:>4} -> {}", tier(s));
}
println!("{}", parse_flag(" YES "));
println!("{}", parse_flag("nope"));
println!("{:?}", first_word(" hello world "));
println!("{:?}", first_word(" "));
}
Output:
-5 -> invalid
0 -> unranked
30 -> bronze
65 -> silver
100 -> gold
true
false
"hello"
"<empty>"
Note the shape of tier: the guard is first because it is the only arm that needs one, and the catch-all is last so the match is exhaustive without restating a condition. first_word is the let ... else payoff -- the happy path is the last line of the function, not the inside of a block.
Real World Example: A Retry Policy for HTTP Responses
Deciding whether to retry a failed request is the classic branching problem. The subject is a status code, the rules are ranges with a few exceptions, and getting it wrong means either hammering a server that told you to stop or giving up on a blip. Here it is as one match returning an enum:
#[derive(Debug, PartialEq)]
enum Action {
Done,
RetryAfter(u32),
Fail(&'static str),
}
const MAX_ATTEMPTS: u32 = 3;
const DEFAULT_BACKOFF: u32 = 2;
fn decide(status: u16, retry_after: Option<u32>, attempt: u32) -> Action {
// A precondition that has nothing to do with the status: return early.
if attempt >= MAX_ATTEMPTS {
return Action::Fail("attempts exhausted");
}
let backoff = retry_after.unwrap_or(DEFAULT_BACKOFF * attempt.max(1));
match status {
200..=299 => Action::Done,
304 => Action::Done,
401 | 403 => Action::Fail("not authorised"),
404 => Action::Fail("not found"),
408 | 425 | 429 => Action::RetryAfter(backoff),
501 => Action::Fail("not implemented"),
500..=599 => Action::RetryAfter(backoff),
code if code < 100 => Action::Fail("not an http status"),
_ => Action::Fail("unhandled status"),
}
}
fn main() {
let cases = [
(200u16, None, 0u32),
(304, None, 0),
(429, Some(30), 0),
(429, None, 2),
(500, None, 1),
(501, None, 0),
(403, None, 0),
(418, None, 0),
(503, None, 3),
];
for (status, retry_after, attempt) in cases {
let action = decide(status, retry_after, attempt);
println!("{status:>4} attempt {attempt} -> {action:?}");
}
}
Output:
200 attempt 0 -> Done
304 attempt 0 -> Done
429 attempt 0 -> RetryAfter(30)
429 attempt 2 -> RetryAfter(4)
500 attempt 1 -> RetryAfter(2)
501 attempt 0 -> Fail("not implemented")
403 attempt 0 -> Fail("not authorised")
418 attempt 0 -> Fail("unhandled status")
503 attempt 3 -> Fail("attempts exhausted")
The reason this is a match and not a chain of if status == ... is that the subject is a single value and the arms are statements about its shape. Written as an if-chain, the reader has to check every condition against every other one to be sure there is no gap and no overlap. Written as a match, the order encodes precedence explicitly -- 501 sits above 500..=599 because it is the exception to it -- and the compiler guarantees there is no gap. Adding a rule is one line in the right position, not a re-read of the whole function.
The early return at the top earns its place because it is about the attempt counter, not the status. Folding it into the match would mean repeating if attempt >= MAX_ATTEMPTS inside every retryable arm, which is exactly the duplication guards tempt you into. The rule of thumb: preconditions that are independent of the subject belong in guard clauses above the match; conditions that refine one particular case belong in a guard on that arm.
Returning an Action rather than, say, a bool plus an Option<u32> is the part that pays off later. With three variants, every caller has to match on the result, and the exhaustiveness check means that the day someone adds Action::RedirectTo(String), the build breaks at each call site that needs to think about it. A bool plus a number cannot do that; it silently accepts a fourth meaning that nobody handles. Enums and match are one feature, and Module 3 is where that pairing gets its own lesson.
#[derive(Debug, PartialEq)] is not decoration either. Debug is what makes the output above possible with {action:?}, and PartialEq means a test can say assert_eq!(decide(429, None, 2), Action::RetryAfter(4)); -- a single expression that pins one rule of the policy. A retry policy is precisely the kind of logic that is cheap to test and expensive to get wrong, and both of those derives cost one line.
Common Mistakes
- Expecting truthiness.
if count { ... }wherecountis an integer giveserror[E0308]: expectedbool, foundi32`. Write the comparison you mean:if count > 0. The same goes for collections --if !list.is_empty(), neverif list`.
- Arms that disagree on type.
let x = if c { 1 } else { "one" };fails witherror[E0308]:ifandelsehave incompatible types. The error points at theelsearm, but the fault is usually that the two branches were written at different times with different intentions.
- An
ifused as an expression with noelse.let x = if c { 1 };is an error: the missing branch would have to produce(). Rust has no implicit zero-value fallback, so supply theelse.
- Putting
_or a bare binding above a specific arm. Everything below it becomes dead code. rustc sayswarning: unreachable pattern, and because it is a warning rather than an error it is easy to scroll past in a noisy build.
- Assuming guards make a
matchexhaustive. Two guards that a human can see cover every case still produceerror[E0004]. The last arm must be a pattern the compiler can reason about on its own.
- Confusing
..and..=in a pattern.0..10stops at nine. Off-by-one in a range arm is silent -- nothing fails to compile, one input just takes the wrong route.
- Reaching for
matchwhen one case matters. A five-linematchwith a_ => {}arm is anif letwritten the long way. Conversely, three nestedif lets that all bail out the same way are amatchon a tuple, or a let chain.
- Moving the subject by accident.
match text { s => s.len() }on aStringbinds by value and moves it, sotextis unusable afterwards. Match on a borrow instead --match &textormatch text.as_str()-- which is also what lets you compare against&strliterals.
- Adding
_to your own enums by reflex. On a type you control, listing every variant is what makes the compiler tell you where to go when you add one. A_arm silently absorbs the new variant and turns a build error into a run-time surprise. (Upstream types marked#[non_exhaustive]are the exception: there a_arm is mandatory.)
Best Practices
- Branch on a value with
matchand on a condition withif. If you find yourself writingif x == A { } else if x == B { }, the subject is a value andmatchwill check your coverage for you.
- Order arms from most specific to most general, with the catch-all last. Treat any
unreachable_patternwarning as a build failure -- it always means an arm you wrote can never run.
- Handle subject-independent preconditions with early
returnabove thematch, and case-specific refinements with a guard on the arm. Never repeat the same guard on several arms.
- Let the branch produce the value:
let x = match ... ;rather than declaringxfirst and assigning inside each arm. One binding means one place to look for wherexcame from.
- Use
let...elsefor bind-or-bail so the happy path stays at the outer indentation level, and reserveif letfor the cases where the non-matching branch actually does something.
- Use
matches!when the answer is abool.matches!(c, 'a'..='z' | 'A'..='Z')says what it means; amatchreturningtrueandfalseburies it.
- Return an enum, not a
boolplus loose data, whenever there are more than two outcomes. The exhaustiveness check only helps at call sites if the type has something to be exhaustive about.
- Avoid
_on enums you own, and preferif letchains or a tuplematchover nesting more than two levels deep. Deep branching in Rust is almost always a sign that the data wants a different shape.
Practice Exercises
- Fizz, buzz, and the exhaustiveness trap. Write
fn label(n: u32) -> Stringthat returns"fizzbuzz"for multiples of 15,"fizz"for multiples of 3,"buzz"for multiples of 5, and the number itself otherwise -- using a singlematchon the tuple(n % 3, n % 5). Then try writing it with guards only, and confirm you geterror[E0004]until the final arm is guard-free. Print the labels for 1 through 20.
- A grade band with a binding. Write
fn band(score: i32) -> Stringthat returns"invalid: -4"for negatives,"F"for 0-59, and otherwise"B (73)"style output usingcode @ 60..=69,code @ 70..=79, and so on up to100. Anything above 100 should return"invalid: 104". Use exactly onematch, and check that you never wrote the same range twice.
- Flatten a nest with
let...else. Givenfn config_port(raw: Option<&str>) -> u16, return8080when the input isNone, when the string does not parse as au16, or when the parsed value is 0. Write it first with nestedif let/match, then rewrite it with twolet...elsestatements and compare the indentation depth of the success path.
- Extend the retry policy. Add a
RetryAftercap of 60 seconds and a newAction::Redirect(u16)variant for 301, 302, 307, and 308, then runcargo buildand fix every error the exhaustiveness check reports inmain. Add threeassert_eq!tests that pin the new behaviour, including one proving that aRetry-Afterheader of 900 is clamped.