studylog/rustlings-conversions #53
Replies: 2 comments 1 reply
-
try_from_into can use: |
Beta Was this translation helpful? Give feedback.
1 reply
-
You can use the following solution for // Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
Self::try_from(&[tuple.0, tuple.1, tuple.2][..])
}
}
// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
Self::try_from(&arr[..])
}
}
// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len() != 3 {
return Err(IntoColorError::BadLen);
}
let res: Result<Vec<_>, _> = slice.iter().cloned().map(u8::try_from).collect();
res.map(|arr| Color {
red: arr[0],
green: arr[1],
blue: arr[2],
})
.map_err(|_| IntoColorError::IntConversion)
}
}
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
studylog/rustlings-conversions
Rust offers a multitude of ways to convert a value of a given type into another type. The simplest form of type conversion is a type cast expression. It is denoted with the binary operator as. For instance, println!("{}", 1 + 1.0); would not compile, since 1 is an integer while 1.0 is a float. However, println!("{}", 1 as f32 + 1.0) should compile. The exercise using_as tries to cover this. Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the convert module. The traits are the following: From and Into covered in from_into TryFrom and TryInto covered in try_from_into AsRef and AsMut covered in as_ref_mutld both compile and run without panicking. These should be the main ways within the standard library to convert data into your desired types. You may find solution code for the topic from my repo.
https://lazyren.github.io/studylog/rustlings-conversions.html
Beta Was this translation helpful? Give feedback.
All reactions