What's the idiomatic way to compare string length in Rust, accounting for the case where the strings are of equal length?
There is a snippet of code in the lifetimes part of the Rust book but it simply returns the latter string if the given strings are of equal length:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
It has been pointed out that .len()
counts the bytes rather than Unicode characters. The desired answer should include a function which returns the longest string in the case that one of the strings is longer in terms of Unicode characters; or something else in the case that the strings are of equal length.