Sub topic 6
Converting Errors Automatically with From
What you need first
This chapter assumes you can write a function that returns Result, and that you know ? returns early on Err. It also assumes you know what the compiler's match-based expansion of ? looks like, and that you can implement a trait for a type. Here you will see how the From trait lets ? change one error type into another.
The problem: two error types in one function
Reading a number from a file can fail in two ways. fs::read_to_string returns io::Error. str::parse returns ParseIntError. A function has only one declared error type, so this does not compile:
use std::fs;
use std::num::ParseIntError;
fn load_count(path: &str) -> Result<u32, ParseIntError> {
let text = fs::read_to_string(path)?;
let n = text.trim().parse::<u32>()?;
Ok(n)
}The first ? has an io::Error and the function promises a ParseIntError. The compiler rejects the call because no conversion from one to the other exists. You need a single error type that can hold both, plus a rule for turning each source error into it. That rule is the From trait.
The From trait
From<T> is a standard library trait that describes how to build a value of your type from a T:
pub trait From<T> {
fn from(value: T) -> Self;
}You write impl From<Source> for Target, and then Target::from(source_value) works. A conversion that cannot fail belongs in From. A fallible one belongs in TryFrom. Error conversion never fails, because wrapping an error in a variant always succeeds.
How ? uses From
In the previous chapter you saw that ? expands to a match with an early return. The important detail is in the Err arm:
Err(e) => return Err(From::from(e)),The ? operator always calls From::from on the error before returning it. The compiler picks the target type from the function's declared return type. If the source error and the declared error type are the same, nothing visible happens, because the standard library provides impl<T> From<T> for T. If they differ, the compiler looks for an impl From<SourceError> for DeclaredError.
Writing the conversions
Define one enum with a variant per source error, then add one From impl per variant. This version of load_count compiles and runs:
use std::fs;
use std::io;
use std::num::ParseIntError;
#[derive(Debug)]
enum LoadError {
Io(io::Error),
Parse(ParseIntError),
}
impl From<io::Error> for LoadError {
fn from(e: io::Error) -> Self {
LoadError::Io(e)
}
}
impl From<ParseIntError> for LoadError {
fn from(e: ParseIntError) -> Self {
LoadError::Parse(e)
}
}
fn load_count(path: &str) -> Result<u32, LoadError> {
let text = fs::read_to_string(path)?;
let n = text.trim().parse::<u32>()?;
Ok(n)
}
fn main() {
match load_count("count.txt") {
Ok(n) => println!("count = {n}"),
Err(e) => println!("failed: {e:?}"),
}
}Each ? in load_count now has a matching impl. The first one uses From<io::Error> and the second uses From<ParseIntError>. The function body contains no conversion code at all. If count.txt is missing, the output is failed: Io(Os { code: 2, kind: NotFound, message: "No such file or directory" }) on Linux. If the file holds abc, you get failed: Parse(ParseIntError { kind: InvalidDigit }).
The next chapter adds Display and Error so this type behaves like a proper error. The conversion mechanism is already complete here.
Rules that decide what compiles
One conversion step only
? performs exactly one From::from call. It does not chain conversions. If A converts to B and B converts to C, a function returning C still cannot use ? on an A. You need impl From<A> for C directly.
The orphan rule
Rust allows impl From<X> for Y only if your crate defines X or Y. In practice the target error type is usually yours, so this is fine. You cannot, however, write impl From<io::Error> for ParseIntError, because both types belong to the standard library. The compiler reports error E0117. When you hit this, define your own wrapper type as the target.
One impl per source type
A type can have only one From<io::Error>. Suppose your error enum needs to tell apart "the config file failed to read" and "the data file failed to read". Both failures produce io::Error, so you cannot give each its own From impl, and the compiler reports conflicting implementations. Even with a single impl, the variant cannot say which file failed.
The identity impl is always there
Because impl<T> From<T> for T exists, a function returning Result<T, MyError> can use ? on another Result<_, MyError> without any extra code. This is why chains of your own functions compose cleanly.
When From is the wrong tool: map_err
From is a good fit when a source error type maps to one meaning. When the same source type needs different meanings, or you want to attach context, convert by hand with map_err and then use ? on the result:
use std::fs;
use std::io;
#[derive(Debug)]
enum ReadError {
Config { path: String, source: io::Error },
Data { path: String, source: io::Error },
}
fn read_both(config: &str, data: &str) -> Result<usize, ReadError> {
let c = fs::read_to_string(config).map_err(|source| ReadError::Config {
path: config.to_string(),
source,
})?;
let d = fs::read_to_string(data).map_err(|source| ReadError::Data {
path: data.to_string(),
source,
})?;
Ok(c.len() + d.len())
}
fn main() {
match read_both("config.toml", "data.csv") {
Ok(n) => println!("{n} bytes"),
Err(e) => println!("error: {e:?}"),
}
}After map_err, the error is already a ReadError. The ? then applies the identity conversion. The two tools combine well. A common design has From impls for the unambiguous cases and map_err for the cases that need context.
| Situation | Use |
|---|---|
| Each source type has one clear meaning | `impl From<Source> for MyError` |
| Same source type, different meanings | `map_err` with a distinct variant |
| You want to add data such as a path | `map_err` with a struct variant |
| You do not care about the exact type | `Box<dyn Error>` (covered later) |
Inference gotchas
The compiler needs to know the source error type at each ?. Normally it does, because the called function's signature states it. Trouble appears in closures with no declared return type. The closure's error type is unconstrained, so many types could receive the conversion, and compilation fails with "type annotations needed". Give the closure an explicit return type:
use std::num::ParseIntError;
fn main() {
let parse = |s: &str| -> Result<i32, ParseIntError> {
let n = s.trim().parse::<i32>()?;
Ok(n * 2)
};
println!("{:?}", parse("21"));
println!("{:?}", parse("x"));
}The same issue shows up with collect and into, where the target type must be named somewhere. A turbofish or a typed let fixes it.
Reading the compiler error
When an impl is missing, the compiler tells you which conversion it wanted. For the LoadError example without From<ParseIntError>, the message says the ? operator couldn't convert the error to LoadError, and that the trait From<ParseIntError> is not implemented for it. Read the error as a to-do item. The name inside From<...> is the source type you need to handle, and the type after for is your declared error. Add that impl, or use map_err at that call site.
Summary of the working model
?on anErr(e)returnsErr(From::from(e)).- The target type is the function's declared error type.
- You supply
impl From<Source> for YourErrorfor each source type. - The identity impl covers matching types, and there is no chaining of conversions.
- One source type maps to one impl. Use
map_errwhen you need more.
Exercise
The function below uses a custom enum AppError with variants Io(io::Error) and Parse(ParseIntError). It has only impl From<io::Error> for AppError. What does the compiler complain about, and what is the smallest change that fixes it?
fn doublefromfile(path: &str) -> Result<i64, AppError> {
let text = std::fs::readtostring(path)?;
let n = text.trim().parse::<i64>()?;
Ok(n * 2)
}
Show answer
The second ? fails because the parse error is a ParseIntError, and AppError has no From<ParseIntError> impl, so the compiler reports that ? couldn't convert the error to AppError. The first ? compiles because From<io::Error> exists. The fix is to add impl From<ParseIntError> for AppError { fn from(e: ParseIntError) -> Self { AppError::Parse(e) } }. Alternatively, write .map_err(AppError::Parse)? on the parse call, which converts at that one site without a new impl.
Exercise
A program reads two files, a.txt and b.txt, and must report which one failed. Why can you not solve this with two variants A(io::Error) and B(io::Error) plus a From<io::Error> impl for each, and what do you do instead?
Show answer
Rust allows only one From<io::Error> impl per target type, so two impls for AppError would conflict, and a single impl could not know which file failed anyway. Instead, drop the From impl for io::Error and call map_err(AppError::A)? on the read of a.txt and map_err(AppError::B)? on the read of b.txt. Each call site picks its own variant.