From 0bed579a4bbca0b788cef986da3cd5117f8cf94f Mon Sep 17 00:00:00 2001 From: Eugen Date: Sat, 29 Nov 2025 19:24:55 +0900 Subject: [PATCH] try_from_into.rs: Improve slice implementation Using pattern matching, we can reduce four bound checks to just one. --- solutions/23_conversions/try_from_into.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/solutions/23_conversions/try_from_into.rs b/solutions/23_conversions/try_from_into.rs index ee802eb06e..15257cf2dc 100644 --- a/solutions/23_conversions/try_from_into.rs +++ b/solutions/23_conversions/try_from_into.rs @@ -52,13 +52,12 @@ impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { - // 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((red, green, blue)) + } else { + Err(IntoColorError::BadLen) } - - // Reuse the implementation for a tuple. - Self::try_from((slice[0], slice[1], slice[2])) } }