Sub topic 1
Result and Option: errors as values
Prerequisites
This chapter assumes you can read basic Rust: functions, structs, enums, and match. You should know what ownership and borrowing mean at a basic level. You should also be able to create and run a project with Cargo.
Errors are ordinary values
Many languages report failure with exceptions. An exception jumps out of the current function and travels up the call stack until something catches it. Nothing in a function's signature tells you it might throw.
Rust takes a different approach. A function that can fail returns a value that says so. The compiler sees that value, and it will not let you use the success data until you have dealt with the possibility of failure.
Two standard enums carry this idea. Both are in the prelude, so you can use them without an import.
Option<T>models a value that may be absent. It has the variantsSome(T)andNone.Result<T, E>models an operation that may fail. It has the variantsOk(T)andErr(E).
Use Option when absence is a normal outcome and needs no explanation. Use Result when the caller needs to know why something failed.
Option in practice
Looking up a key in a map or taking the first element of a list may find nothing. Both return an Option.
fn main() {
let names = vec!["Ada", "Grace"];
match names.first() {
Some(name) => println!("first: {name}"),
None => println!("the list is empty"),
}
let empty: Vec<&str> = Vec::new();
println!("{:?}", empty.first());
}The match must cover both variants. If you remove the None arm, the program does not compile. In languages with null references, forgetting the empty case is a runtime bug. Here it is a compile-time error.
Result in practice
Parsing text into a number can fail, and the reason matters. str::parse returns a Result.
fn main() {
for text in ["42", "forty-two", ""] {
match text.parse::<i32>() {
Ok(n) => println!("{text:?} parsed as {n}"),
Err(e) => println!("{text:?} failed: {e}"),
}
}
}The error type here is ParseIntError. It implements Display, so printing it gives a readable message such as "invalid digit found in string". The E in Result<T, E> can be any type, and a later chapter covers designing your own.
Returning Result from your own functions
Putting Result in a function's return type is how you tell callers that it can fail.
use std::num::ParseIntError;
fn double(text: &str) -> Result<i32, ParseIntError> {
match text.trim().parse::<i32>() {
Ok(n) => Ok(n * 2),
Err(e) => Err(e),
}
}
fn main() {
println!("{:?}", double(" 21 "));
println!("{:?}", double("abc"));
}This prints Ok(42) and then Err(ParseIntError { kind: InvalidDigit }). The function does not decide what to do about a bad input. It reports the error and leaves the decision to the caller.
The Err(e) => Err(e) arm is the pattern to notice. When a function only passes failures along, it repeats this arm everywhere. The ? operator, introduced in a later chapter, replaces it.
Recoverable and unrecoverable errors
Rust splits failures into two groups.
| Kind | Mechanism | Typical cause | Caller can react? |
|---|---|---|---|
| Recoverable | `Result` or `Option` | Missing file, bad input, no match | Yes |
| Unrecoverable | `panic!` | Broken invariant, bug in the program | No, the thread unwinds and stops |
A panic is for situations where continuing would be wrong. Ordinary failures that a user or environment can cause belong in Result. The next chapter covers unwrap, expect, and when a panic is acceptable.
Exercise
You write a function that looks up a user's age in a map by name. Which return type fits best if the only failure is "no such user": Option<u32> or Result<u32, String>? What would change your answer?
Show answer
Option<u32> fits, because absence is the only outcome besides success and needs no explanation. Switch to Result<u32, E> if the caller must distinguish several failure causes, such as "user missing" versus "age field corrupted", or if you want to attach a message.
Exercise
What happens at compile time if a match on a Result<i32, ParseIntError> has only an Ok(n) arm, and why does Rust behave this way?
Show answer
The compiler reports a non-exhaustive patterns error. Rust requires match to cover every variant, which forces you to handle the Err case explicitly instead of ignoring it.