mirror of
https://github.com/rust-lang/rustlings.git
synced 2025-12-28 06:49:19 +00:00
try_from_into.rs: Improve slice implementation
Using pattern matching, we can reduce four bound checks to just one.
This commit is contained in:
parent
b5d440fdc3
commit
0bed579a4b
@ -52,13 +52,12 @@ impl TryFrom<&[i16]> for Color {
|
||||
type Error = IntoColorError;
|
||||
|
||||
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
|
||||
// Check the length.
|
||||
if slice.len() != 3 {
|
||||
return Err(IntoColorError::BadLen);
|
||||
}
|
||||
|
||||
if let &[red, green, blue] = slice {
|
||||
// Reuse the implementation for a tuple.
|
||||
Self::try_from((slice[0], slice[1], slice[2]))
|
||||
Self::try_from((red, green, blue))
|
||||
} else {
|
||||
Err(IntoColorError::BadLen)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user