Skip to main content

How to Handle a Result with match in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
match result {
Ok(value) => expression_using_value,
Err(error) => expression_using_error,
}
PartWhat it does
resultA 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​

Terminal
cargo new demo
cd demo
Output
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:

src/main.rs, which defines describe, matching input.parse as an i32 with an Ok arm that prints the number and an Err arm that prints not a number with the error, and calls it with 42 and forty-two.

src/main.rs
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 an i32 and returns a Result.
  • Ok(number) => runs when it worked, with the number in number.
  • Err(err) => runs when it didn't, with the error in err, which {err} prints as text.

Step 3: Run It​

Terminal
cargo run -q
Output
42: the number 42
forty-two: not a number (invalid digit found in string)

A zsh terminal where cargo run -q prints 42: the number 42, then 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 the Ok arm ran with the number 42.
  • "forty-two" didn't, so the Err arm ran, and the error's text, invalid digit found in string, said why.
  • The program handled the bad input and finished. With unwrap() instead of match, "forty-two".parse::<i32>().unwrap() stopped the program with called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the Err armerror[E0004]: non-exhaustive patterns: `Err(_)` not coveredAdd 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 typesMake every arm give the same type
unwrap() on input that can be wrongThe program stops at the first bad valuematch on the Result

Troubleshooting​

SymptomLikely causeFix
non-exhaustive patterns: `Err(_)` not coveredA match with only an Ok armAdd the Err arm
non-exhaustive patterns: `Ok(_)` not coveredA match with only an Err armAdd the Ok arm
`match` arms have incompatible typesThe arms give values of different typesGive 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​