Skip to content

Commit 0bed579

Browse files
authored
try_from_into.rs: Improve slice implementation
Using pattern matching, we can reduce four bound checks to just one.
1 parent b5d440f commit 0bed579

1 file changed

Lines changed: 5 additions & 6 deletions

File tree

solutions/23_conversions/try_from_into.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,12 @@ impl TryFrom<&[i16]> for Color {
5252
type Error = IntoColorError;
5353

5454
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
55-
// Check the length.
56-
if slice.len() != 3 {
57-
return Err(IntoColorError::BadLen);
55+
if let &[red, green, blue] = slice {
56+
// Reuse the implementation for a tuple.
57+
Self::try_from((red, green, blue))
58+
} else {
59+
Err(IntoColorError::BadLen)
5860
}
59-
60-
// Reuse the implementation for a tuple.
61-
Self::try_from((slice[0], slice[1], slice[2]))
6261
}
6362
}
6463

0 commit comments

Comments
 (0)