Sub topic 1
Result and the ? operator: a quick refresher
Every later chapter in this tutorial builds on two features: the Result type and the ? operator. This chapter reviews how they work and shows where they stop being enough. By the end you will know exactly what ? does when it meets an error. Custom error types and the From trait both depend on that behavior.
Prerequisites
This chapter assumes you already know the following:
- Basic Rust syntax, including enums and
match. - The
OptionandResulttypes at a basic level. - How traits work, including how to call a trait method and read a trait bound.
- How to create a project with Cargo and run it with
cargo run.
You do not need any external crates yet. Everything here uses the standard library.
Result: failure as a value
Rust has no exceptions. A function that can fail says so in its return type, using Result<T, E> from the standard library:
enum Result<T, E> {
Ok(T),
Err(E),
}T is the type of the success value. E is the type of the error value. The caller must handle both cases before using the value, because the compiler will not let you treat a Result<u16, _> as a u16.
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse::<u16>()
}
fn main() {
for input in ["8080", "http"] {
match parse_port(input) {
Ok(port) => println!("port {port}"),
Err(e) => println!("error: {e}"),
}
}
}Running this prints:
port 8080
error: invalid digit found in stringHere E is ParseIntError, a type defined by the standard library. The error type is part of the function's signature, so callers can see what kind of failure to expect.
What the ? operator does
Handling every Result with match gets tedious when several fallible calls follow one another. The ? operator is shorthand for "unwrap the success value, or return the error from this function."
These two functions behave the same way:
use std::num::ParseIntError;
fn with_match(s: &str) -> Result<u16, ParseIntError> {
let port = match s.trim().parse::<u16>() {
Ok(value) => value,
Err(e) => return Err(From::from(e)),
};
Ok(port)
}
fn with_question_mark(s: &str) -> Result<u16, ParseIntError> {
let port = s.trim().parse::<u16>()?;
Ok(port)
}The match version is a close approximation. The compiler's real expansion goes through the Try trait, but the model above predicts the behavior correctly. It shows three facts:
- On
Ok(value), the expressionexpr?evaluates tovalueand execution continues. - On
Err(e), the enclosing function returns immediately. - The returned error passes through
From::from, so it can change type on the way out.
The third fact matters most for this tutorial.
The From conversion
The error that ? returns does not have to be the same type as the error it found. It only has to be convertible, which means the function's error type F must implement From<E> for the found error type E. If it does not, the code does not compile:
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, String> {
// Does not compile: String does not implement From<ParseIntError>.
let port = s.trim().parse::<u16>()?;
Ok(port)
}The compiler reports error E0277, "? couldn't convert the error to String", and notes that From<ParseIntError> is not implemented. This is the most common ? error you will meet, and the rest of the tutorial exists to solve it well.
You have three ways to fix it.
Convert by hand with map_err
map_err transforms the error inside a Result and leaves the success value alone:
fn parse_port(s: &str) -> Result<u16, String> {
let port = s
.trim()
.parse::<u16>()
.map_err(|e| format!("bad port {s:?}: {e}"))?;
Ok(port)
}This works, but the error is now just text. Callers cannot inspect it or ask what caused it.
Use Box<dyn Error>
The standard library implements From<E> for Box<dyn Error> for every type E that implements std::error::Error. A function returning Result<T, Box<dyn Error>> can therefore use ? on many different error types:
use std::error::Error;
use std::fs;
fn sum_from_file(path: &str) -> Result<u32, Box<dyn Error>> {
let text = fs::read_to_string(path)?; // io::Error becomes Box<dyn Error>
let mut total = 0;
for line in text.lines() {
let n: u32 = line.trim().parse()?; // ParseIntError becomes Box<dyn Error>
total += n;
}
Ok(total)
}This is convenient. The cost is that the caller only sees a boxed trait object. It cannot match on the failure without extra work. The anyhow crate, covered later, is a more capable version of this idea.
Define your own error type
You can write a type that implements From for each error you want ? to absorb. That gives callers a precise, matchable error. It takes more code by hand, and thiserror removes most of that code. Both approaches get their own chapters.
Where ? is allowed
The ? operator returns from the function it appears in, so that function's return type must be compatible. Three rules cover most cases:
?on aResultneeds a function that returns aResult.?on anOptionneeds a function that returns anOption.?inside a closure returns from the closure, not from the surrounding function.
Option and Result do not mix directly. Convert one into the other first:
fn first_digit(s: &str) -> Result<u32, String> {
let c = s.chars().next().ok_or("empty input")?;
let digit = c
.to_digit(10)
.ok_or_else(|| format!("{c:?} is not a digit"))?;
Ok(digit)
}ok_or turns None into Err with a ready-made value. ok_or_else takes a closure, so it builds the error only when needed. The first ? works even though ok_or("empty input") produces an &str error, because String implements From<&str>.
Returning Result from main
main can return a Result too, which lets you use ? at the top level. The error type must implement Debug:
fn main() -> Result<(), std::num::ParseIntError> {
let n: i32 = "x".parse()?;
println!("{n}");
Ok(())
}When main returns Err, Rust prints the error with its Debug format to standard error and exits with a nonzero status code. This program prints:
Error: ParseIntError { kind: InvalidDigit }That message is accurate but unfriendly. It shows no file name, no explanation, and no hint about what the program was trying to do. Fixing that is the main job of the later chapters on anyhow and error context.
Handy Result methods
? handles propagation. These methods handle the other situations you meet when working with a Result:
| Method | What it does | Typical use |
|---|---|---|
| `map_err(f)` | Transforms the `Err` value | Changing or wrapping an error |
| `map(f)` | Transforms the `Ok` value | Post-processing a success |
| `and_then(f)` | Chains another fallible step | Sequencing without `?` |
| `ok()` | Turns `Result` into `Option`, dropping the error | When the failure reason does not matter |
| `unwrap_or(v)` | Returns the value or a default | Safe fallbacks |
| `expect(msg)` | Returns the value or panics with `msg` | Tests, or impossible failures |
Common mistakes
- Using
?in a function that returns(). The compiler says?can only be used in a function that returnsResultorOption. Change the return type, or handle the error withmatch. - Forgetting the final
Ok(()). A function returningResult<(), E>must end withOk(())once all the?calls succeed. - Reaching for
unwrapin library code.unwrappanics, so it takes the decision about failure away from the caller. Return aResultinstead. - Discarding the cause with
map_err(|_| ...). This throws away the original error. Keep it as a field of your new error, or include its message.
Why this is not the whole story
Result and ? give you the mechanism, but not the design. A plain String error loses structure. Box<dyn Error> loses the concrete type. A hand-written enum keeps both, but requires a good deal of boilerplate. The next chapters look at what makes a type a proper error, then use thiserror for precise types and anyhow for application code.
Exercise
This function does not compile. Explain why, and give two different fixes. fn read_count(s: &str) -> Result<u32, String> { let n = s.trim().parse::<u32>()?; Ok(n) }
Show answer
The ? operator converts the error with From::from, and String does not implement From<ParseIntError>, so the compiler reports E0277. Fix 1: convert the error by hand with s.trim().parse::<u32>().map_err(|e| e.to_string())?. Fix 2: change the return type to Result<u32, Box<dyn std::error::Error>>, because Box<dyn Error> implements From for any type that implements Error.
Exercise
What does this program print to standard error, and what exit status does it return? Why is the message hard to act on? fn main() -> Result<(), std::num::ParseIntError> { let n: u8 = "300".parse()?; println!("{n}"); Ok(()) }
Show answer
It prints Error: ParseIntError { kind: PosOverflow } and exits with a nonzero status. The value 300 is too large for a u8, so parsing fails. main prints the Debug form of the error, which names neither the input nor the operation that failed. Adding that context is the job of the anyhow chapters.