Sub topic 11
Result and the ? operator
This chapter assumes you know basic Rust syntax, how Option and match work, and the basics of ownership. By the end you will be able to return a Result from a function, handle it with match, and use ? to pass errors up to the caller.
What Result is
Result<T, E> is an enum in the standard library. It has two variants:
Ok(T)holds the value of a successful operation.Err(E)holds a description of what went wrong.
Option says that a value may be absent. Result says that an operation may fail, and it keeps the reason. Because it is an enum, the compiler makes you handle both variants before you can use the value inside. Rust also marks Result as #[must_use]. If you ignore a returned Result, you get a warning.
Handling a Result with match
Parsing text into a number is a common fallible operation. str::parse returns a Result.
fn parse_age(text: &str) -> Result<u8, std::num::ParseIntError> {
text.trim().parse::<u8>()
}
fn main() {
for input in ["42", " 7 ", "abc", "300"] {
match parse_age(input) {
Ok(age) => println!("{input:?} -> age {age}"),
Err(e) => println!("{input:?} -> error: {e}"),
}
}
}The input "300" fails because it does not fit in a u8. The Err value carries a ParseIntError, which prints a readable message.
Propagating errors with ?
Often a function cannot do anything useful with an error. It should pass the error to its caller. Writing that by hand with match is verbose:
use std::num::ParseIntError;
fn sum_verbose(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = match a.parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(e),
};
let y = match b.parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(e),
};
Ok(x + y)
}The ? operator does the same job. Placed after an expression of type Result, it does one of two things:
- If the value is
Ok(v), the expression evaluates tov. - If the value is
Err(e), the enclosing function returns early withErr(e).
use std::num::ParseIntError;
fn sum(a: &str, b: &str) -> Result<i32, ParseIntError> {
Ok(a.parse::<i32>()? + b.parse::<i32>()?)
}
fn main() {
println!("{:?}", sum("2", "40"));
println!("{:?}", sum("2", "x"));
}Rules for using ?
The ? operator only works inside a function whose return type can accept the failure. The common errors are these:
- Using
?inmainwhenmainreturns(). The compiler reports that the?operator can only be used in a function that returnsResultorOption. Change the signature tofn main() -> Result<(), Box<dyn std::error::Error>>, or handle the error withmatch. - Mixing types.
?on aResultneeds a function that returnsResult.?on anOptionneeds a function that returnsOption. To switch between them, useok_or(OptiontoResult) or.ok()(ResulttoOption). - Mismatched error types. If the function's error type differs from the one
?sees, the error goes throughFrom::from. If noFromimplementation exists, the code does not compile.
The last rule is the basis for custom error enums, which a later chapter covers.
Useful Result methods
Not every case needs match. These methods cover common needs.
| Method | Effect |
|---|---|
| `unwrap_or(default)` | Returns the `Ok` value, or the default on `Err`. |
| `map(f)` | Transforms the `Ok` value and leaves `Err` unchanged. |
| `map_err(f)` | Transforms the `Err` value and leaves `Ok` unchanged. |
| `ok()` | Converts to `Option`, discarding the error. |
| `unwrap()` | Returns the `Ok` value, or panics on `Err`. |
Use unwrap only in tests, quick experiments, or cases where failure is impossible. In other code, a panic turns a recoverable error into a crash.
Returning errors from main
A main function can return Result. If it returns Err, the program prints the error with its Debug format and exits with a non-zero status code.
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let port: u16 = "8080".parse()?;
println!("listening on {port}");
let bad: u16 = "eighty".parse()?;
println!("unreachable: {bad}");
Ok(())
}Box<dyn Error> accepts any error type that implements the Error trait, so ? can convert many kinds of errors into it.
Exercise
A function has the signature fn load(a: &str) -> Result<i32, String> and its body calls a.parse::<i32>()?. Will it compile? Explain why or why not, and give one fix.
Show answer
It will not compile. parse::<i32>() returns Result<i32, ParseIntError>, and ? must convert ParseIntError into String with From. No such From implementation exists. A fix is to map the error first: a.parse::<i32>().map_err(|e| e.to_string())?.
Exercise
What happens if you write let n: i32 = "5".parse()?; inside a main declared as fn main() with no return type?
Show answer
It does not compile. ? needs the enclosing function to return Result (or Option). main returns (), so the compiler rejects the code. Change the signature to fn main() -> Result<(), Box<dyn std::error::Error>> and end the body with Ok(()).