The From trait enables automatic conversion of one error type into another, allowing the ? operator to propagate errors seamlessly. Implementing From<SourceError> for your custom error type tells Rust how to transform SourceError into your error variant.
use std::fmt;
#[derive(Debug)]
struct MyError(String);
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for MyError {}
impl From<std::io::Error> for MyError {
fn from(err: std::io::Error) -> Self {
MyError(format!("IO error: {}", err))
}
}
fn read_file() -> Result<String, MyError> {
std::fs::read_to_string("data.txt")? // Automatically converts io::Error to MyError
}