Sub topic 6
Converting errors automatically with From
This chapter assumes you know how ? returns early on Err and how to define an enum and implement a trait for it. It covers the conversion step that ? performs on the error value.
The problem: two error types in one function
A function that returns Result<T, E> has exactly one error type E. Real functions often call several operations that fail in different ways. Parsing fails with ParseIntError. Reading a file fails with io::Error. Your own checks fail with whatever you define.
? solves this by calling From::from on the error before returning it. If the error type in the failing call differs from the one in your signature, the compiler looks for an impl From<ThatError> for YourError.
The From trait
From is a standard library trait with one method:
trait From<T> {
fn from(value: T) -> Self;
}impl From<A> for B means "a B can be built from an A". The conversion cannot fail and takes ownership of the input. The standard library also provides impl<T> From<T> for T, which does nothing. That is why ? works when the error types already match.
What happens at each ?
The target type is fixed by the function's return type. The source type comes from the expression before ?.
A worked example
This program defines an error enum and one From implementation. It runs as shown.
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Parse(ParseIntError),
Negative(i32),
}
impl From<ParseIntError> for AppError {
fn from(e: ParseIntError) -> Self {
AppError::Parse(e)
}
}
fn parse_positive(s: &str) -> Result<i32, AppError> {
let n: i32 = s.trim().parse()?;
if n < 0 {
return Err(AppError::Negative(n));
}
Ok(n)
}
fn main() {
println!("{:?}", parse_positive("42"));
println!("{:?}", parse_positive("-3"));
println!("{:?}", parse_positive("abc"));
}The output is:
Ok(42)
Err(Negative(-3))
Err(Parse(ParseIntError { kind: InvalidDigit }))The ? on parse() sees a ParseIntError and a function that returns AppError. It calls AppError::from(e), which wraps the original error in the Parse variant. The Negative error needs no conversion because you build it directly.
One From impl per source type
Add one impl From<X> for AppError for each error type you want ? to absorb. A function can then mix ? on io::Error and ParseIntError with no manual matching. Each source type needs its own variant, or a variant that holds enough information to tell the cases apart.
When From is the wrong tool
From maps by type alone, so it cannot add context. Two different ParseIntError sources, such as a port and a retry count, look the same to ?. Use map_err to choose a specific variant at that call site:
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
BadPort(ParseIntError),
BadRetries(ParseIntError),
}
fn read(port: &str, retries: &str) -> Result<(u16, u8), ConfigError> {
let p = port.parse::<u16>().map_err(ConfigError::BadPort)?;
let r = retries.parse::<u8>().map_err(ConfigError::BadRetries)?;
Ok((p, r))
}Here map_err already produces a ConfigError, so ? converts it with the identity From<T> for T. No From<ParseIntError> impl is needed.
Common error: missing conversion
If no matching From impl exists, compilation fails with error E0277. The message says that ? couldn't convert the error to your type, and that the trait From<ParseIntError> is not implemented for it. The fix is either to add the impl or to call map_err before ?.
Exercise
A function returns Result<u16, ConfigError>. Inside it you call "80".parse::<u16>()?. ConfigError has no From impl. What two changes can fix the compile error, and which one lets you choose different variants for different parse calls?
Show answer
Either add impl From<ParseIntError> for ConfigError, or call .map_err(...) with a function that builds a ConfigError before the ?. The map_err approach lets you pick a different variant at each call site. A From impl always picks the same one for a given source type.