Rustlings errors6.rs

This is my first time posting, so please be kind. For rustlings errors6.rs this approach works, but I would like to refactor more.

use std::num::ParseIntError;

// This is a custom error type that we will be using in `parse_pos_nonzero()`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
    Creation(CreationError),
    ParseInt(ParseIntError),
}

impl From<ParseIntError> for ParsePosNonzeroError {
    fn from(err: ParseIntError) -> Self {
        ParsePosNonzeroError::ParseInt(err)
    }
}

impl From<CreationError> for ParsePosNonzeroError {
    fn from(err: CreationError) -> Self {
        ParsePosNonzeroError::Creation(err)
    }
}

fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
    let n: i64 = s.parse()?;
    let n = PositiveNonzeroInteger::new(n)?;
    Ok(n)
}

Is it possible to replace these impl From functions with a macro? I tried to use this Trait Implementation, but was unsuccessful.

Thanks,
coopers

You can use https://docs.rs/thiserror/latest/thiserror/ to do it, with #[from] attribute from the derive macro Error.

#[derive(PartialEq, Debug, Error)]
enum ParsePosNonzeroError {
    #[error("creation error")]
    Creation(#[from] CreationError),
    #[error("integer parsing error")]
    ParseInt(#[from] ParseIntError),
}

#[derive(PartialEq, Debug, Error)]
#[error("creation error")]
struct CreationError;

code

2 Likes

Thanks vague. That works.