Sub topic 1
Result and Option: errors as values
Rust has no exceptions. A function that can fail says so in its return type, and the caller must deal with that. This chapter covers the two types that carry that information, Result and Option, and the habits the rest of this tutorial builds on.
Prerequisites
This chapter assumes you already know:
- Basic Rust syntax: functions, structs, enums, and
match. - Ownership and borrowing basics.
- What it means to implement a trait for a type.
- How to build and run a project with Cargo.
You do not need to know the ? operator yet. Later chapters introduce it.
Errors as values
In many languages, a failing function throws an exception. The signature does not show this, and control jumps to some handler far away. Rust treats a failure as an ordinary value that the function returns. The signature shows that failure is possible, and the compiler will not let you use the success value without first handling the other case.
Rust splits failures into two groups:
- Recoverable errors are expected in normal operation. A file may not exist, or a user may type text where a number belongs. The program can report the problem or try something else. These use
ResultandOption. - Unrecoverable errors are bugs or broken invariants, such as indexing past the end of a vector. These cause a panic, which unwinds the stack and ends the thread. The next chapter covers panics.
The rest of this chapter covers the recoverable kind.
The Option type
Option<T> models a value that may be absent. It is an enum in the standard library:
enum Option<T> {
Some(T),
None,
}Rust has no null reference. Where another language would return null, Rust returns Option. The standard library uses it widely. For example, Vec::get returns None for an out-of-range index, and str::find returns None when the text is not found.
fn main() {
let numbers = vec![10, 20, 30];
match numbers.get(1) {
Some(n) => println!("found {n}"),
None => println!("no element at that index"),
}
match numbers.get(7) {
Some(n) => println!("found {n}"),
None => println!("no element at that index"),
}
}Option says that something is missing. It does not say why. That is acceptable when there is only one possible reason, such as "the list is empty" or "the key is not in the map".
The Result type
Result<T, E> models an operation that either succeeds with a T or fails with an E:
enum Result<T, E> {
Ok(T),
Err(E),
}The Err variant carries information about the failure. Parsing a string into a number is a typical case:
fn main() {
let good = "42".parse::<i32>();
let bad = "forty-two".parse::<i32>();
println!("{good:?}");
println!("{bad:?}");
}This prints:
Ok(42)
Err(ParseIntError { kind: InvalidDigit })The error type here is std::num::ParseIntError. Each fallible standard library function has its own error type, and later chapters show how to combine several of them.
Option versus Result
The two types are close relatives. Use this table to choose between them.
| Question | `Option<T>` | `Result<T, E>` |
|---|---|---|
| Success variant | `Some(T)` | `Ok(T)` |
| Failure variant | `None` | `Err(E)` |
| Failure carries a reason | No | Yes |
| Typical meaning | A value may not exist | An operation may fail |
| Example | `HashMap::get` | `File::open` |
A good rule is to ask whether the caller needs to know why it failed. If it does, return a Result. If absence is the only thing to report, return an Option.
The compiler makes you handle both cases
Both types are enums, so you cannot reach the inner value without matching on the variant. This code does not compile:
fn main() {
let n = "42".parse::<i32>();
let doubled = n * 2;
println!("{doubled}");
}The compiler rejects it because Result<i32, ParseIntError> is not a number, and you cannot multiply it. You must say what happens in the Err case. This is the main benefit of errors as values: a forgotten error check becomes a compile error and not a runtime surprise.
There is a softer safety net as well. Result is marked #[must_use], so ignoring a returned Result produces a warning:
use std::fs;
fn main() {
fs::remove_file("old.log");
}The compiler warns about an unused Result that must be used. Silencing the warning on purpose with let _ = ...; is a visible choice, which is what you want from code that drops an error.
A first complete example
The function below parses a string into an age and rejects values that make no sense. It returns a Result with a String as its error, which is simple but enough for now.
fn parse_age(input: &str) -> Result<u8, String> {
match input.trim().parse::<u8>() {
Ok(age) if age <= 150 => Ok(age),
Ok(age) => Err(format!("{age} is not a believable age")),
Err(e) => Err(format!("could not read '{input}' as a number: {e}")),
}
}
fn main() {
for text in ["34", " 7 ", "200", "abc", "-5"] {
match parse_age(text) {
Ok(age) => println!("age is {age}"),
Err(message) => println!("error: {message}"),
}
}
}The output is:
age is 34
age is 7
error: 200 is not a believable age
error: could not read 'abc' as a number: invalid digit found in string
error: could not read '-5' as a number: invalid digit found in stringNotes on this code:
- The function has three outcomes, and each has an arm. The
if age <= 150guard separates a valid number from an implausible one. "200"parses as au8becauseu8holds 0 to 255. The range check is a separate rule on top of the type."-5"fails to parse becauseu8has no negative values.- Using
Stringas the error type loses structure. A caller cannot tell the two failure kinds apart without reading the text. The chapter on custom error types fixes this.
Passing values through a call chain
Real programs call fallible functions from other fallible functions. Without help, every layer needs its own match:
use std::num::ParseIntError;
fn double(input: &str) -> Result<i32, ParseIntError> {
match input.trim().parse::<i32>() {
Ok(n) => Ok(n * 2),
Err(e) => Err(e),
}
}
fn quadruple(input: &str) -> Result<i32, ParseIntError> {
match double(input) {
Ok(n) => Ok(n * 2),
Err(e) => Err(e),
}
}
fn main() {
println!("{:?}", quadruple("5"));
println!("{:?}", quadruple("five"));
}In both functions, the Err(e) => Err(e) arm does nothing except pass the error to the caller. This pattern is called error propagation. It is so common that Rust gives it a dedicated operator, ?. The following chapters build up to it step by step, and you will see this exact function rewritten in a single line.
Edge cases to keep in mind
OptionandResultare different types. A function that returnsOption<T>cannot return anErr, and the reverse is also true. Moving between them takes an explicit conversion, covered in a later chapter.Errdoes not mean the program failed. It is only a value. Whether the program stops depends on what the code does with it.- The error type is part of the signature.
Result<i32, ParseIntError>andResult<i32, String>are different types, and the compiler will not treat them as interchangeable. Result<(), E>is common. The unit type()as the success type means the operation produces no value, but it can still fail. Writing to a file is an example.Option<Option<T>>andResult<Option<T>, E>are legal. The second form is useful when "not found" is a normal outcome and "the lookup itself failed" is a different one.
Summary of the model
Exercise
A function find_user(id: u32) looks up a user in a list. When the user is missing, the caller only needs to know that fact. When the list is stored in a file that may fail to load, the caller needs to know what went wrong. Which return type fits each case: Option<User> or Result<User, E>? Explain why.
Show answer
For the in-memory lookup where a missing user is the only failure, Option<User> fits, because absence is the only thing to report and there is no reason to carry. For the file-backed lookup, Result<User, E> fits, because loading can fail for several reasons (missing file, bad permissions, corrupt data) and the caller needs the error value to tell them apart. A common design is Result<Option<User>, E>, which separates "the lookup failed" from "the user does not exist".
Exercise
Why does let doubled = "42".parse::<i32>() * 2; fail to compile, and what is the minimum change that makes it work using only match?
Show answer
The parse call returns Result<i32, ParseIntError>, which is an enum and does not support multiplication. The code must handle both variants, for example: let doubled = match "42".parse::<i32>() { Ok(n) => n * 2, Err(_) => 0 };. The Err arm needs some policy, here a default of 0, though returning the error to the caller is often better.