How to Convert Between Error Types in Rust

Implement the From trait to define how Rust converts specific error types into your custom error enum for use with the ? operator.

You convert error types in Rust by implementing the From trait for your custom error type to define the conversion logic. This allows you to use the ? operator to automatically convert errors from one type to another within functions that return Result<T, YourErrorType>.

use std::fmt;

#[derive(Debug)]
enum MyError {
    Io(std::io::Error),
    Parse(std::num::ParseIntError),
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MyError::Io(e) => write!(f, "IO error: {}", e),
            MyError::Parse(e) => write!(f, "Parse error: {}", e),
        }
    }
}

impl std::error::Error for MyError {}

impl From<std::io::Error> for MyError {
    fn from(err: std::io::Error) -> Self {
        MyError::Io(err)
    }
}

impl From<std::num::ParseIntError> for MyError {
    fn from(err: std::num::ParseIntError) -> Self {
        MyError::Parse(err)
    }
}

fn process_data() -> Result<i32, MyError> {
    let input = std::fs::read_to_string("data.txt")?;
    let value: i32 = input.trim().parse()?;
    Ok(value)
}