Sub topic 11
Result and the ? operator
Option<T> says a value may be missing. Result<T, E> says an operation may fail, and it carries the reason. This chapter covers how Result is built, how to handle it, and how the ? operator removes most of the repetitive error handling. It assumes you know the match expression, Option, and basic ownership. Custom error enums get their own chapter, so here we use the error types the standard library provides.
Result is an ordinary enum
Result is defined in the standard library like this:
enum Result<T, E> {
Ok(T),
Err(E),
}It has two generic parameters. T is the type of the success value and E is the type of the error value. Both variants are in the prelude, so you write Ok(5) and Err(e) without importing anything. Because it is an enum, everything you know about match applies, including exhaustiveness: you cannot forget the Err case.
fn main() {
for text in ["42", "-7", "forty"] {
match text.parse::<i32>() {
Ok(n) => println!("parsed {n}"),
Err(e) => println!("cannot parse {text:?}: {e}"),
}
}
}str::parse::<i32> returns Result<i32, ParseIntError>. The third input prints cannot parse "forty": invalid digit found in string. The error value is a real type, so you can print it, inspect it, or pass it upward.
The type is also marked #[must_use]. If you call a function that returns a Result and ignore the value, the compiler warns you. A failure cannot be dropped silently by accident.
Handling a Result without a full match
A full match is often more than you need. These methods cover the common cases.
| Method | What it does | Use when |
|---|---|---|
| `unwrap()` | Returns the `Ok` value, or panics on `Err` | Prototypes and tests |
| `expect("msg")` | Same, but panics with your message | A failure means a bug in your program |
| `unwrap_or(default)` | Returns the `Ok` value, or the default | A fallback value is acceptable |
| `unwrap_or_else(f)` | Computes the fallback from the error | The fallback is costly or depends on the error |
| `map(f)` | Transforms the `Ok` value, passes `Err` through | You want to change the success value |
| `map_err(f)` | Transforms the `Err` value, passes `Ok` through | You want to change the error type |
| `and_then(f)` | Runs a second fallible step on the `Ok` value | You are chaining fallible steps |
| `ok()` | Converts to `Option<T>` and discards the error | You do not care why it failed |
| `ok_or(e)` (on `Option`) | Converts to `Result<T, E>` using `e` as the error | You want a missing value to count as an error |
if let Ok(n) = text.parse::<i32>() also works when you only care about the success branch. unwrap and expect turn an error into a panic that ends the thread, so keep them out of code that handles input you do not control.
The ? operator
Chains of match expressions that only forward errors get tiresome. Here is a function that parses two numbers without ?:
use std::num::ParseIntError;
fn sum_pair_verbose(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = match a.trim().parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(e),
};
let y = match b.trim().parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(e),
};
Ok(x + y)
}
fn main() {
println!("{:?}", sum_pair_verbose("2", " 3 "));
}The ? operator replaces each of those match blocks:
use std::num::ParseIntError;
fn sum_pair(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = a.trim().parse::<i32>()?;
let y = b.trim().parse::<i32>()?;
Ok(x + y)
}
fn main() {
println!("{:?}", sum_pair("2", " 3 "));
println!("{:?}", sum_pair("2", "x"));
}This prints Ok(5) and then Err(ParseIntError { kind: InvalidDigit }). Placed after an expression of type Result<T, E>, ? does one of two things:
- If the value is
Ok(v), the whole expression evaluates tovand execution continues. - If the value is
Err(e), the enclosing function returns immediately withErr(e).
Error conversion through From
The Err branch is slightly more than return Err(e). It calls From::from(e) first, so the error is converted into the function's declared error type. When the two types are the same, the conversion does nothing. When they differ, the function compiles only if a From implementation exists between them.
This is why one function can use ? on calls that fail with different error types. The usual tool for that is Box<dyn Error>, which can hold any standard error:
use std::error::Error;
use std::fs;
fn read_port(path: &str) -> Result<u16, Box<dyn Error>> {
let text = fs::read_to_string(path)?;
let port = text.trim().parse::<u16>()?;
Ok(port)
}
fn main() -> Result<(), Box<dyn Error>> {
let port = read_port("port.txt")?;
println!("port {port}");
Ok(())
}read_to_string fails with std::io::Error and parse fails with ParseIntError. Both convert into Box<dyn Error>. If port.txt does not exist, main returns the error, and the runtime prints it with the Debug format and exits with a non-zero status. Writing your own error enum and From implementations is the subject of a later chapter.
Where ? is allowed
? only works inside a function whose return type can absorb the early return. The two common cases are Result and Option. Using it in a function that returns () is a compile error.
Using ? with Option
? also works on Option<T> in a function that returns Option. None returns early and Some(v) becomes v.
fn first_word_len(s: &str) -> Option<usize> {
let word = s.split_whitespace().next()?;
Some(word.len())
}
fn main() {
println!("{:?}", first_word_len("hello world"));
println!("{:?}", first_word_len(" "));
}This prints Some(5) and then None.
You cannot use ? on an Option inside a function that returns Result, or the reverse. The compiler does not convert between them for you. You convert explicitly: ok_or or ok_or_else turns an Option into a Result, and ok() turns a Result into an Option.
fn first_number(s: &str) -> Result<i32, String> {
let word = s.split_whitespace().next().ok_or("empty input")?;
word.parse::<i32>()
.map_err(|e| format!("bad number {word:?}: {e}"))
}
fn main() {
println!("{:?}", first_number("12 apples"));
println!("{:?}", first_number("apples"));
println!("{:?}", first_number(""));
}Here ok_or("empty input") produces Result<&str, &str>, and ? converts the &str error into String through From<&str> for String. The map_err call builds a readable message from the parse failure. The output is:
Ok(12)
Err("bad number \"apples\": invalid digit found in string")
Err("empty input")Collecting many Results
When you have an iterator of Result values, collect can gather them into a single Result<Vec<_>, _>. It stops at the first Err and returns it. If every item is Ok, you get the vector of unwrapped values.
use std::num::ParseIntError;
fn parse_all(items: &[&str]) -> Result<Vec<i32>, ParseIntError> {
items.iter().map(|s| s.parse::<i32>()).collect()
}
fn main() {
println!("{:?}", parse_all(&["1", "2", "3"]));
println!("{:?}", parse_all(&["1", "two", "3"]));
}The first call prints Ok([1, 2, 3]). The second prints the ParseIntError for "two" and never looks at "3".
Common mistakes
- Using
unwrapon input from users, files, or the network. Return the error with?and let the caller decide. - Throwing away the cause with
.ok()when the caller needs to know why the operation failed. - Returning
Result<T, String>everywhere. It works, but callers cannot match on the kind of failure. Once callers need to distinguish errors, move to an error enum. - Expecting
?to convert betweenOptionandResulton its own. Useok_ororok(). - Adding context only at the top level. Use
map_errclose to the failure so the message says which step failed.
Exercise
What does let n = text.parse::<i32>()?; do when text is "abc" inside a function returning Result<i32, ParseIntError>, and what does n hold when text is "12"?
Show answer
With "abc", parse returns Err(ParseIntError). The ? operator returns that error from the enclosing function immediately, and the rest of the function does not run. With "12", parse returns Ok(12), ? unwraps it, and n holds the i32 value 12.
Exercise
Write a function fn add_strs(a: &str, b: &str) -> Result<i32, String> that parses both arguments as i32 and returns their sum. On a parse failure, the error string must name the argument that failed. Use ? and map_err.
Show answer
fn addstrs(a: &str, b: &str) -> Result<i32, String> {
let x = a.parse::<i32>().maperr(|e| format!("first argument {a:?}: {e}"))?;
let y = b.parse::<i32>().maperr(|e| format!("second argument {b:?}: {e}"))?;
Ok(x + y)
}
Each `maperr converts the ParseIntError into a String, so the error type matches the declared return type, and ? then returns it early. addstrs("1", "2") gives Ok(3), and addstrs("1", "z") gives an Err whose text starts with second argument "z"`.