How to convert between error types

Convert between error types in Rust by implementing the From trait for your custom error enum and using the ? operator for automatic propagation.

You convert between error types in Rust by implementing the From trait for your custom error type or by using the ? operator with the Into trait to propagate errors. Define a custom error enum and implement From for the types you want to convert into it, then use ? to automatically convert and propagate errors in functions returning Result.

use std::io;

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

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

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

fn read_and_parse() -> Result<i32, AppError> {
    let input = io::stdin().read_line()?; // Converts io::Error to AppError
    let value: i32 = input.trim().parse()?; // Converts ParseIntError to AppError
    Ok(value)
}