Sub topic 12
From and the ? operator
This chapter shows how the ? operator uses the From trait to convert errors as they propagate. It assumes you know basic Rust syntax, Result and Option, how impl Trait for Type works, and the From and Into basics from the previous chapters.
What ? actually does
The ? operator unwraps a Result if it holds Ok. If it holds Err, the function returns early with that error. There is one extra step: the error goes through From::from first.
For let n = expr?;, the compiler produces roughly this:
let n = match expr {
Ok(value) => value,
Err(e) => return Err(From::from(e)),
};The error type in the function's return type decides which From implementation runs. If the function returns Result<T, PortError> and expr fails with a ParseIntError, the compiler needs impl From<ParseIntError> for PortError. Without it, the code does not compile.
When the two error types are the same, the call still works. The standard library provides impl<T> From<T> for T, which returns the value unchanged.
A complete example
This code appeared earlier in the tutorial. Here the focus is on how ? uses it.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum PortError {
Parse(ParseIntError),
OutOfRange(i64),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::Parse(e) => write!(f, "not a number: {}", e),
PortError::OutOfRange(n) => write!(f, "port {} is out of range", n),
}
}
}
impl From<ParseIntError> for PortError {
fn from(e: ParseIntError) -> Self {
PortError::Parse(e)
}
}
fn parse_port(s: &str) -> Result<u16, PortError> {
let n: i64 = s.trim().parse()?;
u16::try_from(n).map_err(|_| PortError::OutOfRange(n))
}
fn main() {
println!("{:?}", parse_port("8080"));
match parse_port("abc") {
Ok(p) => println!("port {}", p),
Err(e) => println!("error: {}", e),
}
if let Err(e) = parse_port("70000") {
println!("error: {}", e);
}
}Two lines in parse_port handle errors in different ways:
s.trim().parse()?produces aParseIntErroron failure. TheFromimpl wraps it inPortError::Parseautomatically.u16::try_from(n)produces a different error type,TryFromIntError. There is noFrom<TryFromIntError> for PortError, so the code usesmap_errto buildPortError::OutOfRangeby hand.
The enum's Display implementation makes the message readable. Debug is derived so the error can be printed with {:?} or returned from main.
Several error sources, one error type
A function often fails in more than one way. Give the error enum one variant per source and one From impl per variant. Then each ? picks the right conversion from the type of the error it sees.
use std::fmt;
use std::fs;
use std::io;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Io(io::Error),
Parse(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Io(e) => write!(f, "I/O error: {}", e),
ConfigError::Parse(e) => write!(f, "bad number: {}", e),
}
}
}
impl From<io::Error> for ConfigError {
fn from(e: io::Error) -> Self {
ConfigError::Io(e)
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::Parse(e)
}
}
fn read_count(path: &str) -> Result<u32, ConfigError> {
let text = fs::read_to_string(path)?;
let n = text.trim().parse::<u32>()?;
Ok(n)
}
fn main() {
match read_count("does-not-exist.txt") {
Ok(n) => println!("count: {}", n),
Err(e) => println!("error: {}", e),
}
}The first ? sees an io::Error and calls From<io::Error>. The second sees a ParseIntError and calls the other impl. Each source type can have only one From impl for a given target, so the compiler never has to guess.
Box<dyn Error> as a catch-all
For small programs you can skip the custom enum. The standard library implements From<E> for Box<dyn Error> for every type E that implements Error. It also implements From<&str> and From<String>, so a plain message can become an error with .into().
use std::error::Error;
fn double(s: &str) -> Result<i32, Box<dyn Error>> {
let n: i32 = s.parse()?;
if n > 1000 {
return Err("too big".into());
}
Ok(n * 2)
}
fn main() -> Result<(), Box<dyn Error>> {
println!("{}", double("21")?);
println!("{}", double("x")?);
Ok(())
}This prints 42, then the process exits with status 1 and reports Error: ParseIntError { kind: InvalidDigit } on stderr. When main returns Err, Rust prints the error with Debug, not Display. That is one reason to derive Debug on every error type.
The trade-off is that callers receive a Box<dyn Error> and cannot match on specific variants. Use Box<dyn Error> in applications and scripts. Use a custom enum in libraries, where callers need to react to specific failures.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `` `?` couldn't convert the error to `MyError` `` | No `impl From<SourceError> for MyError` | Add the impl, or use `map_err` |
| `` the `?` operator can only be used in a function that returns `Result` or `Option` `` | `?` used in a function returning `()` | Change the return type, for example `fn main() -> Result<(), E>` |
| Mismatched types when using `?` on an `Option` | `Option` and `Result` are not mixed implicitly | Convert with `.ok_or(err)?` |
| Error says two impls conflict | Two `From<X>` impls for the same pair of types | Keep one, and use `map_err` for the other meaning |
| Cannot implement `From<ForeignA> for ForeignB` | Orphan rule: your crate must own one of the types | Wrap one of them in your own type |
When map_err is better than From
A From impl is chosen by type alone. Suppose a function reads two files and both can fail with io::Error. A single From<io::Error> impl cannot say which file failed. In that case, convert explicitly and attach the context:
use std::fs;
#[derive(Debug)]
enum LoadError {
Settings(std::io::Error),
Cache(std::io::Error),
}
fn load() -> Result<(String, String), LoadError> {
let settings = fs::read_to_string("settings.txt").map_err(LoadError::Settings)?;
let cache = fs::read_to_string("cache.txt").map_err(LoadError::Cache)?;
Ok((settings, cache))
}
fn main() {
println!("{:?}", load().is_ok());
}Here LoadError::Settings is a function, so it can be passed straight to map_err. The ? that follows still runs From, but it is the identity conversion because the types already match.
Key points
?returns early onErrand callsFrom::fromon the error first.- The function's declared error type picks the
Fromimpl. One impl per source type. From<T> for Tmakes?work when no conversion is needed.Box<dyn Error>accepts anyErrortype and also strings.- Use
map_errwhen the conversion depends on context rather than on type.
Exercise
A function returns Result<u8, AppError>. Its body contains let n: u8 = text.parse()?;, where text is a &str. The code fails to compile with "? couldn't convert the error to AppError". What exactly is missing, and what does the minimum fix look like?
Show answer
Parsing a u8 fails with std::num::ParseIntError, and there is no impl From<ParseIntError> for AppError. The minimum fix is to add one, for example impl From<ParseIntError> for AppError { fn from(e: ParseIntError) -> Self { AppError::Parse(e) } }, where AppError has a Parse(ParseIntError) variant. Alternatively, replace ? with .map_err(AppError::Parse)?, which needs no From impl.
Exercise
A function reads a.txt and b.txt with fs::read_to_string, and the caller must be able to tell which file failed. Why is a single impl From<io::Error> for MyError the wrong tool, and what should you use instead?
Show answer
From is selected by the source error type alone. Both reads fail with io::Error, so one impl cannot know which file was involved. Use map_err on each call with a different variant, such as MyError::A and MyError::B, each holding the io::Error.
Exercise
A main function is declared as fn main() -> Result<(), Box<dyn Error>> and returns an Err. Which formatting trait does Rust use to print the error, and what is the process exit status?
Show answer
Rust prints the error with Debug (as Error: ... on stderr), and the exit status is 1 (a failure).