The Analogy: The Two Channels at Customs
Every arriving passenger goes down exactly one of two channels. Nothing to declare, or something to declare. Not neither -- there is no third door and no way to slip past the desk -- and not both. That is what match on a Result is: the compiler standing at the arrivals hall making sure every possible passenger has a channel to walk down, and refusing to open the terminal until one exists.
The interesting work happens after the split, and it happens in the declaration channel. "Something to declare" is not a response; it is a category that immediately subdivides. A bottle of wine over the allowance gets a duty calculation. An undeclared firearm gets a phone call. A bag of soil gets an incinerator. The officer's script branches on what was declared, not merely on the fact that something was, and this is why matching an error usually means matching its variants and their contents rather than stopping at Err(e).
At the end of the desk there is often a sign that says, in effect, wave everything else through. It is efficient, it keeps the queue moving, and it is exactly where the next unfamiliar category of goods will walk out unexamined. A _ arm on an error enum is that sign. It is sometimes correct and it is always a decision, because the moment somebody adds a variant, every desk with that sign keeps working and starts being wrong.
Finally: an officer can open a bag, look inside, and hand it back, or they can take it away for good. Rust distinguishes those, and the distinction is not decoration. Matching a Result by value takes the contents; matching a reference to it lets you look and leave the envelope intact for whoever needs it next.
Syntax or Core Structure
A match on a Result is an expression, so all its arms produce a value of the same type, and the patterns can reach as deep into the Ok and Err payloads as you like.
fn main() {
let inputs = ["8", "0", "-3", "x", "300"];
for s in inputs {
let outcome = match s.parse::<i8>() {
Ok(0) => String::from("zero, nothing to do"),
Ok(n) if n < 0 => format!("{n} is negative"),
Ok(n) => format!("{n} accepted"),
Err(e) => format!("rejected: {e}"),
};
println!("{s:>4} -> {outcome}");
}
}
Output:
8 -> 8 accepted
0 -> zero, nothing to do
-3 -> -3 is negative
x -> rejected: invalid digit found in string
300 -> rejected: number too large to fit in target type
Three of those arms match Ok, and they are tried top to bottom: the literal Ok(0), then the guarded Ok(n) if n < 0, then the catch-all Ok(n). Move that last one to the front and the two above it become unreachable -- which the compiler will tell you about, because an unreachable pattern is almost always a bug.
The Compiler Insists On Both Channels
fn main() {
let r: Result<i32, String> = Ok(1);
match r {
Ok(n) => println!("{n}"),
}
}
Output (trimmed; rustc also prints where Result is defined and a help: offering to insert the arm):
error[E0004]: non-exhaustive patterns: `Err(_)` not covered
--> src/main.rs:4:11
|
4 | match r {
| ^ pattern `Err(_)` not covered
|
= note: the matched value is of type `Result<i32, String>`
This is the single most valuable thing Result gives you, and it is worth being precise about why. It is not that the compiler dislikes missing arms. It is that "I forgot to handle the failure" is the most common bug in error handling in every language that lets you forget, and here it is not a runtime surprise, a warning, or a code review comment. It is a build failure.
Technical Depth: Matching The Error, Not Just The Failure
Err(e) => println!("{e}") is where most people stop, and it throws away the reason you designed an error type in the first place. The standard library's own errors are built for this: io::Error carries a kind() precisely so that callers can branch.
use std::fs;
use std::io::ErrorKind;
fn main() {
match fs::read_to_string("settings.toml") {
Ok(text) => println!("read {} bytes", text.len()),
Err(e) => match e.kind() {
ErrorKind::NotFound => println!("no settings file; using defaults"),
ErrorKind::PermissionDenied => println!("cannot read settings: check permissions"),
_ => println!("unexpected error reading settings: {e}"),
},
}
}
Output (run in a directory with no settings.toml):
no settings file; using defaults
"File not found" and "permission denied" are the same Result variant and completely different situations. The first is often not an error at all -- a missing optional config is a normal first run -- while the second is a deployment problem somebody needs to fix. A caller that stops at Err(e) cannot tell them apart.
Note that the _ arm here is required, not optional. ErrorKind is marked #[non_exhaustive], which is the standard library reserving the right to add kinds without breaking your build. You cannot exhaustively match it even if you list every variant that exists today.
The Wildcard Arm Is A Commitment
On your error enum the choice is yours, and it is a real one.
| You write | What happens when you add a variant |
|---|---|
every variant listed, no _ | every match fails to compile -- the compiler hands you the list of sites to update |
a _ arm | everything compiles and silently mishandles the new case |
#[non_exhaustive] on the enum | other crates are forced to write _, and you may add variants freely |
The first row is the reason to prefer exhaustive matches inside your own crate: adding a variant becomes a guided tour of everywhere that decision matters. The third row is the reason public error enums are usually marked #[non_exhaustive]: you cannot hand every downstream crate a compile error every time you learn about a new failure mode.
The _ arm has one shape that is almost always fine: when it genuinely does the same thing for everything left over, and that thing is "report it and carry on". The shape to be suspicious of is a _ arm that makes a decision -- retry, ignore, default -- because that decision was made without knowing what it is deciding about.
Looking Versus Taking
Matching a Result by value consumes it, which is fine right up until you want it afterwards.
| Written as | r afterwards | s is bound as |
|---|---|---|
match r | moved | String |
match &r | still usable | &String |
match r.as_ref() | still usable | &String |
match r { Ok(ref s) => ... | still usable | &String, the pre-2018 spelling |
fn main() {
let r: Result<String, String> = Ok(String::from("payload"));
match &r {
Ok(s) => println!("ok, {} bytes", s.len()),
Err(e) => println!("err {e}"),
}
match r.as_ref() {
Ok(s) => println!("again, still {} bytes", s.len()),
Err(e) => println!("err {e}"),
}
match r {
Ok(s) => println!("finally owning {s}"),
Err(e) => println!("err {e}"),
}
}
Output:
ok, 7 bytes
again, still 7 bytes
finally owning payload
Notice that matching &r against the pattern Ok(s) works without writing &Ok(s) or Ok(ref s). That is match ergonomics: when the value being matched is a reference and the pattern is not, the bindings become references automatically. It is why modern Rust code almost never contains the ref keyword, and why match &r is usually the shortest correct thing to write.
The difference between &r and r.as_ref() is small but real. &r gives you &Result<T, E> and the patterns bind by reference. as_ref() gives you an actual Result<&T, &E> -- a new Result holding references -- which you can then feed to combinators like map that consume what they are given. Reach for &r when you are matching and as_ref() when you are chaining.
if let, and let-else
When only one channel interests you, a whole match is noise.
fn main() {
let inputs = ["12", "oops"];
for s in inputs {
if let Ok(n) = s.parse::<u32>() {
println!("{s:>4} doubled is {}", n * 2);
}
}
for s in inputs {
let Ok(n) = s.parse::<u32>() else {
println!("{s:>4} skipped");
continue;
};
println!("{s:>4} tripled is {}", n * 3);
}
}
Output:
12 doubled is 24
12 tripled is 36
oops skipped
let ... else is the one to learn properly, because it produces the flattest possible code: the happy path continues at the outer indentation level, and the failure path is a block that must diverge -- continue, break, return or a panic. The compiler enforces the divergence, so there is no way to fall out of the else and carry on with an unbound n.
Both forms share one trap: neither gives you the error. if let Ok(n) discards it, and inside a let ... else block the error is not bound to anything -- the pattern that failed did not name it. If the reason matters, that is a match, not an if let.
Nested Results Flatten Into One Match
A Result whose Ok is itself a Result turns up more often than you would like: a thread handle that joined successfully but whose thread returned an error, a request that arrived but whose body would not parse, a transaction that committed but whose payload was rejected. The instinct is a match inside a match. You do not need one.
fn outer(flag: u8) -> Result<Result<u32, String>, String> {
match flag {
0 => Err(String::from("could not reach the service")),
1 => Ok(Err(String::from("service said no"))),
_ => Ok(Ok(42)),
}
}
fn main() {
for flag in 0..3 {
match outer(flag) {
Err(e) => println!("{flag}: transport -- {e}"),
Ok(Err(e)) => println!("{flag}: response -- {e}"),
Ok(Ok(n)) => println!("{flag}: value {n}"),
}
}
}
Output:
0: transport -- could not reach the service
1: response -- service said no
2: value 42
Three arms, one level of indentation, and the three genuinely different situations named side by side. This is the shape to reach for whenever the layers of failure mean different things -- and if they do not mean different things, the layers should not have been nested in the first place.
Naming What You Also Want To Test
@ binds a name to a value while still matching a pattern against it, which is what you want whenever the range is the interesting part and the exact number is what you print.
fn check(code: u32) -> Result<u32, u32> {
if code < 400 {
Ok(code)
} else {
Err(code)
}
}
fn main() {
for code in [200, 204, 301, 404, 500, 999] {
let text = match check(code) {
Ok(c @ 200..=299) => format!("success ({c})"),
Ok(c) => format!("unexpected success code {c}"),
Err(c @ 400..=499) => format!("client error ({c})"),
Err(c @ 500..=599) => format!("server error ({c})"),
Err(c) => format!("unknown status {c}"),
};
println!("{code} -> {text}");
}
}
Output:
200 -> success (200)
204 -> success (204)
301 -> unexpected success code 301
404 -> client error (404)
500 -> server error (500)
999 -> unknown status 999
Without @ you would have to choose between the range check and the value, and end up writing a guard (Ok(c) if (200..=299).contains(&c)) that says the same thing less directly. Range patterns come in two forms: 200..=299 includes both ends, and 200..300 excludes the upper one. Both are limited to types with a sensible notion of adjacency -- integers, char, and a handful of other primitives -- so you cannot range-match a String.
The last arm is worth a look. Err(c) catches 999 -- a status code that is not a real HTTP status at all -- and reports it as unknown rather than pretending it is a server error. That arm exists because the type is u32 and u32 can hold 999. A newtype that could only hold real status codes would have removed the arm and the class of bug with it.
Real World Example: Deciding What To Do With A Failed Job
A queue worker is the clearest case for matching an error properly, because every failure mode has a different correct response and getting it wrong costs either throughput or money.
#[derive(Debug)]
enum JobError {
Timeout { after_ms: u32 },
RateLimited { retry_after_s: u32 },
BadRequest(String),
Unauthorized,
Server { status: u32 },
}
enum Action {
RetryNow,
RetryAfter(u32),
Requeue,
Discard(String),
Escalate(String),
}
fn decide(attempt: u32, outcome: Result<u32, JobError>) -> Action {
match outcome {
Ok(ms) => Action::Discard(format!("done in {ms} ms")),
Err(JobError::Timeout { after_ms }) if attempt < 3 => {
Action::RetryAfter(after_ms / 1000 + 1)
}
Err(JobError::Timeout { after_ms }) => {
Action::Escalate(format!("timed out after {after_ms} ms on attempt {attempt}"))
}
Err(JobError::RateLimited { retry_after_s }) => Action::RetryAfter(retry_after_s),
Err(JobError::BadRequest(why)) => Action::Discard(format!("will never work: {why}")),
Err(JobError::Unauthorized) => Action::Escalate(String::from("credentials rejected")),
Err(JobError::Server { status: 503 }) => Action::Requeue,
Err(JobError::Server { .. }) if attempt < 3 => Action::RetryNow,
Err(JobError::Server { status }) => Action::Escalate(format!("HTTP {status} persisted")),
}
}
fn describe(a: &Action) -> String {
match a {
Action::RetryNow => String::from("retry immediately"),
Action::RetryAfter(s) => format!("retry in {s}s"),
Action::Requeue => String::from("back of the queue"),
Action::Discard(why) => format!("discard -- {why}"),
Action::Escalate(why) => format!("escalate -- {why}"),
}
}
And the worker loop:
fn main() {
let outcomes: [(u32, Result<u32, JobError>); 9] = [
(1, Ok(412)),
(1, Err(JobError::Timeout { after_ms: 5000 })),
(4, Err(JobError::Timeout { after_ms: 5000 })),
(1, Err(JobError::RateLimited { retry_after_s: 30 })),
(2, Err(JobError::BadRequest(String::from("missing field 'to'")))),
(1, Err(JobError::Unauthorized)),
(1, Err(JobError::Server { status: 503 })),
(1, Err(JobError::Server { status: 500 })),
(5, Err(JobError::Server { status: 500 })),
];
let mut retried = 0;
let mut finished = 0;
for (attempt, outcome) in outcomes {
let label = match &outcome {
Ok(_) => String::from("ok"),
Err(e) => format!("{e:?}"),
};
let action = decide(attempt, outcome);
match &action {
Action::RetryNow | Action::RetryAfter(_) | Action::Requeue => retried += 1,
Action::Discard(_) | Action::Escalate(_) => finished += 1,
}
println!("attempt {attempt} {label}");
println!(" -> {}", describe(&action));
}
println!();
println!("{retried} to retry, {finished} finished");
}
Output:
attempt 1 ok
-> discard -- done in 412 ms
attempt 1 Timeout { after_ms: 5000 }
-> retry in 6s
attempt 4 Timeout { after_ms: 5000 }
-> escalate -- timed out after 5000 ms on attempt 4
attempt 1 RateLimited { retry_after_s: 30 }
-> retry in 30s
attempt 2 BadRequest("missing field 'to'")
-> discard -- will never work: missing field 'to'
attempt 1 Unauthorized
-> escalate -- credentials rejected
attempt 1 Server { status: 503 }
-> back of the queue
attempt 1 Server { status: 500 }
-> retry immediately
attempt 5 Server { status: 500 }
-> escalate -- HTTP 500 persisted
4 to retry, 5 finished
Every arm in decide is a decision that only a match could express, because the right response depends on the shape and the contents of the failure. Timeout on attempt 1 and Timeout on attempt 4 are the same error and opposite actions. Server { status: 503 } and Server { status: 500 } are the same variant and different actions. No chain of combinators expresses that: map_err can rename an error and unwrap_or can replace it, but only a match can route on it.
Three pattern features carry the weight. Guards let two arms share a pattern and differ on context the error itself does not contain -- attempt is not part of JobError, and it should not be, because the error describes what the service said and the attempt count belongs to the worker. A literal inside a variant, Server { status: 503 }, matches one value in one field, and it has to sit above the general Server arms or it will never fire; arm order is strictly top to bottom. And Server { .. } ignores the fields entirely, which is how the middle arm avoids an unused-variable warning while still saying which variant it wants.
decide returns an Action instead of performing one, and that separation is the part worth stealing. The matching is a pure function from an attempt count and an outcome to a decision, so the whole retry policy is testable without a queue, a clock, a network or a single await. The loop is the only thing that acts. Reading decide top to bottom tells you the complete policy on one screen, rather than reconstructing it from the call sites that happen to raise each error.
The honest limits. The counting match uses or-patterns across variants and has no _ arm, which is deliberate: add an Action::Split tomorrow and the build breaks here, which is the entire argument of the wildcard section made concrete. RetryAfter(after_ms / 1000 + 1) turns a 5000 ms timeout into a 6 second wait by integer division plus one, and that is a made-up backoff -- no exponential growth, no jitter, no ceiling, and no good reason for a retry delay to be derived from how long the last attempt hung. BadRequest(String) carries prose, so the discard reason is printable and never inspectable; that is exactly the mistake the previous lesson warned about, left in on purpose because this is how easily it happens when one variant "just needs a message". And attempt: u32 is a bare number with no bound in the type and no statement anywhere of whether attempts count from 0 or 1 -- the guards say < 3, and whether that means three tries or four is a question the code does not answer.
Common Mistakes
- A
_arm on your own error enum. It compiles today and keeps compiling forever, including on the day somebody adds the variant that needed different handling. If you want a wildcard, put#[non_exhaustive]on the enum so the choice is explicit rather than accidental.
- Putting the general arm above the specific one.
Err(JobError::Server { .. })beforeErr(JobError::Server { status: 503 })makes the 503 arm dead. The compiler warns about unreachable patterns, so read that warning instead of scrolling past it.
- Matching by value when you need the
Resultafterwards.match rmoves it. Reach formatch &rby default and only take ownership in the arm that actually needs the payload.
if let Ok(n)where the error mattered. There is no arm for it, so it is gone. This is the quietest way to lose an error in Rust, and it looks tidy, which is what makes it dangerous.
- Expecting a failed guard to end the match. A guard runs after its pattern matches, and if the guard is false the match keeps going to the next arm.
Ok(n) if n > 0followed by nothing that handles zero or negatives is a non-exhaustive match, and the compiler counts it that way -- guards never contribute to exhaustiveness.
Err(e) => panic!("{e}")written out by hand. That isunwrapwith more lines and a worse location. The next lesson covers when it is the right call and how to say so in one word.
- Matching on error message text.
Err(e) if e.to_string().contains("not found")binds your logic to somebody else's wording. Usekind(), a variant, or a code.
- Assuming your
ErrorKindmatch is exhaustive.io::ErrorKindis#[non_exhaustive]; you will always need a_, and it will always be the arm that handles the failure you did not anticipate.
- Nesting a match inside a match for nested
Results.Ok(Ok(v)),Ok(Err(e))andErr(e)are three patterns at one level. Two levels of indentation for the same information is harder to read and easier to get wrong.
Best Practices
- List the variants; earn the wildcard. Inside your own crate, an exhaustive match turns "I added a variant" into a checklist of every place that has to think about it.
- Default to
match &result. It is one character, it never moves anything, and match ergonomics mean the patterns look identical to the by-value version.
- Match the error's contents, not its existence. If two failures deserve different responses, the arms should say so. If they never will, the error type has too many variants.
- Use guards for context the error does not carry -- attempt counts, deadlines, feature flags -- and put anything intrinsic to the failure inside the error instead.
- Return a decision rather than performing one. A matching function that yields an enum of actions is testable in isolation and readable in one pass; a matching function full of side effects is neither.
- Reach for
let ... elsefor the early-exit shape. It keeps the happy path unindented and makes the compiler prove that the failure branch cannot fall through.
- Flatten nested
Results into one set of patterns, and use@when you want to range-check a value and also print it.
- Mark public error enums
#[non_exhaustive]. It is a promise you are going to want, and adding it later is itself a breaking change.
Practice Exercises
- Break it on purpose. Add
Action::Split(u32)to theActionenum and compile. Note every location the compiler flags, then add a_arm to the counting match, add another variant, and note how many it flags this time.
- Read the unreachable warning. Move the
Err(JobError::Server { .. })arm above theErr(JobError::Server { status: 503 })arm, compile, and record the warning. Then predict, before running, what the twoServer { status: 500 }rows and the503row will print, and check.
- Route on success too. Change the
Okarm so that a job taking over 300 ms producesAction::Escalatewhile a faster one still producesAction::Discard, using a guard and then again using an@range pattern. Say which version you would keep.
- Three ways to build the label. Rewrite the
labelcomputation as (a) thematch &outcomeit is now, (b) anif let, and (c) a combinator chain ending inunwrap_or_else. For each, state what happens to the error value and which one you would put in a code review.