Hi all,
I've been starting rust for a couple of days, and really enjoy it. Rustlings is a well made tutorial and I do recommend it to any new learner.
Still, I've been struggling with this "try_from_into.rs" exercise, where the hint asked the following challenge :
Can you make the
TryFrom
implementations generic over many integer types?
I jumped into it, and implementd a (somehow) working solution. But I am not satisfied by the result of how I manage Errors.
Especially, I would like to use the "?" operator everywhere, but I can't find out how to make it work.
Here is the (partial) code :
#[derive(Debug, PartialEq)]
enum IntoColorError {
// Incorrect length of slice
BadLen,
// Integer conversion error
IntConversion,
}
impl<T: TryInto<u8>> TryFrom<(T, T, T)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (T, T, T)) -> Result<Self, Self::Error> {
let (in_red, in_green, in_blue) = tuple;
try_from_color_values(in_red, in_green, in_blue)
}
}
fn try_from_color_values<T: TryInto<u8>>(
in_red: T,
in_green: T,
in_blue: T,
) -> Result<Color, IntoColorError> {
// Here, I would like to prevent the "or()" call and use "?" instead
let blue = in_blue.try_into().or(Err(IntoColorError::IntConversion))?;
let green = in_green.try_into().or(Err(IntoColorError::IntConversion))?;
let red = in_red.try_into().or(Err(IntoColorError::IntConversion))?;
Ok(Color { blue, green, red })
}
If I change into in_blue.try_into()?;
, then I get compilation error :
error[E0277]: `?` couldn't convert the error to `IntoColorError`
let blue = in_blue.try_into()?;
| ^ the trait `From<<T as std::convert::TryInto<u8>>::Error>` is not implemented for `IntoColorError`
Whatever I do, I can't implement the "From" trait correctly.
Do you have any ideas what is wrong or how I can make it work ?