Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
pawelngei opened this issue Oct 26, 2023 · 0 comments

Comments

@pawelngei
Copy link

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 #816 (comment) , 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 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant