Swapped longest into its declarative form.

The function was ment to use the functional programming style, however,
I forgot to uncomment and swap out the imperative style.
This commit is contained in:
2025-07-02 15:39:19 -04:00
parent d16f8e333e
commit 32595d41bb

View File

@ -52,20 +52,26 @@ pub fn longest<'a>(strings: &'a [String]) -> Option<&'a str>
return None;
}
// Imperative programming style.
//
// ```Rust
// This is the current longest string. (index, length)
// let mut longest: (usize, usize) = (0, 0);
// for (index, string) in strings.iter().enumerate()
// {
// if string.len() > longest.1
// {
// longest = (index, string.len());
// }
// }
//
// Some(&strings[longest.0])
// ```
//
// This can also be done with functional style:
// strings.iter().max_by_key(|s| s.len()).map(|s| s.as_str())
let mut longest: (usize, usize) = (0, 0);
for (index, string) in strings.iter().enumerate()
{
if string.len() > longest.1
{
longest = (index, string.len());
}
}
Some(&strings[longest.0])
// When coding prefer the functional, declarative style.
// It is just as fast or faster than the imperative style.
strings.iter().max_by_key(|s| s.len()).map(|s| s.as_str())
}