How to Handle a Result with match in Rust
Rust functions that can fail return a Result: Ok with a value, or Err with an error. match handles both, with one arm for each, so the program carries on either way instead of stopping.
Syntax
match result {
Ok(value) => expression_using_value,
Err(error) => expression_using_error,
}
| Part | What it does |
|---|---|
result | A Result: either Ok with a value or Err with an error. |
Ok(value) => | The arm that runs on success. value is the value inside the Ok. |
Err(error) => | The arm that runs on failure. error is the error inside the Err. |
, | Ends each arm. |
The documentation for std::result: "Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value." The Rust Book on match: "Matches in Rust are exhaustive: We must exhaust every last possibility in order for the code to be valid."
The Example
The example's describe function turns its text into an i32 with parse, which returns a Result, and matches it: the Ok arm prints the number, and the Err arm prints the error. main calls it with "42" and with "forty-two".
Prerequisites
- Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.1.
Step 1: Create a Project
cargo new demo
cd demo
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.
Step 2: Write the Code
Replace the contents of src/main.rs with:

fn describe(input: &str) {
match input.parse::<i32>() {
Ok(number) => println!("{input}: the number {number}"),
Err(err) => println!("{input}: not a number ({err})"),
}
}
fn main() {
describe("42");
describe("forty-two");
}
input.parse::<i32>()tries to turn the text into ani32and returns aResult.Ok(number) =>runs when it worked, with the number innumber.Err(err) =>runs when it didn't, with the error inerr, which{err}prints as text.
Step 3: Run It
cargo run -q
42: the number 42
forty-two: not a number (invalid digit found in string)

cargo run compiles the program and runs it, and -q hides Cargo's own status lines.
What Happened
"42"parsed, so theOkarm ran with the number 42."forty-two"didn't, so theErrarm ran, and the error's text,invalid digit found in string, said why.- The program handled the bad input and finished. With
unwrap()instead ofmatch,"forty-two".parse::<i32>().unwrap()stopped the program withcalled `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out the Err arm | error[E0004]: non-exhaustive patterns: `Err(_)` not covered | Add an Err arm; Err(_) => if you don't need the error |
Arms that give different types, such as Ok(n) => n, Err(e) => "bad" | error[E0308]: `match` arms have incompatible types | Make every arm give the same type |
unwrap() on input that can be wrong | The program stops at the first bad value | match on the Result |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
non-exhaustive patterns: `Err(_)` not covered | A match with only an Ok arm | Add the Err arm |
non-exhaustive patterns: `Ok(_)` not covered | A match with only an Err arm | Add the Ok arm |
`match` arms have incompatible types | The arms give values of different types | Give every arm the same type |
FAQ
Can a match give back a value?
Yes. match is an expression: with Ok(n) => n and Err(_) => 0 as its arms, let n = match "4".parse::<i32>() { ... }; stored 4 in n. That's why every arm has to give the same type.
match, if let or the ? operator?
match handles every outcome where it stands. if let handles one pattern, such as only Ok, and skips the rest. ? doesn't handle the error at all: it returns it from the current function, to the caller.
Conclusion
match result { Ok(value) => ..., Err(error) => ... } runs one arm for each outcome of a Result, and the compiler makes sure no outcome is left out.
Additional Resources
- std::result, in the standard library documentation.
- The match Control Flow Construct, in the Rust Book, and match expressions, in the Rust Reference.
