Is the reason I have to specify lifetimes in the longest
function below that Rust doesn't want to assume that every value in the strings
parameter array has the same lifetime? I was thinking lifetimes are only required in function signatures where two or more arguments are references, the return type is a reference, and one of the reference arguments is returned.
fn longest<'a>(strings: &'a [&str]) -> &'a str {
strings
.iter()
.fold("", |acc, s| if s.len() > acc.len() { s } else { acc })
}
fn main() {
let fruits = ["apple", "banana", "cherry", "date"];
let result = longest(&fruits);
println!("longest is {}", result);
}
Output:
longest is banana
Errors:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.12s
Running `target/debug/playground`