rustlings icon indicating copy to clipboard operation
rustlings copied to clipboard

`try_from_into.rs` solution without using Box - helper function or `From<TryFromIntError>`?

Open pawelngei opened this issue 2 years ago • 0 comments

Hello!

I'm a beginner in Rust and just finished the Rustling for the first time! I have to admit that try_from_into gave me the most problems, as I was struggling with an idiomatic way to map errors with ? without repeating the lines.

I found multiple solutions, both in https://users.rust-lang.org/t/help-me-get-the-most-from-this-rustling-try-from-into-rs/62749/3 and local issues, like https://github.com/rust-lang/rustlings/issues/816#issuecomment-894892635 , but all of them seemed to imply that we need to use a Box<dyn error:Error>, which not only is not what the exercise asks you for, but also is not possible with assert_eq! tests, giving you the following error:

error[E0369]: binary operation `==` cannot be applied to type `Result<Color, Box<dyn std::error::Error>>`

The best idiomatic solution I encountered required me to write a helper function, which used .map_err. We could of course do it on a per-line basis, but that's repeating a lot of code. Such a solution could be found at https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f3a7d27fe7cb4c2144e8c1878086be6a , with the function in question:

fn parse_color(color: i16) -> Result<u8, IntoColorError> {
  color.try_into().map_err(|_e| IntoColorError::IntConversion)
}

// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
    type Error = IntoColorError;
    fn try_from((red, green, blue): (i16, i16, i16)) -> Result<Self, Self::Error> {
        Ok(Color {
            red: parse_color(red)?,
            green: parse_color(green)?,
            blue: parse_color(blue)?
        })
    }
}

Does this solution cover the goal of the exercise?

Or should we, as michcia suggested on Mastodon, go along implementing impl From<TryFromIntError> for IntoColorError to allow try_into? The full playground is available at https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=13a8149fbcb5d292ac43faeed3824332 .

pawelngei avatar Oct 26 '23 17:10 pawelngei