I've started to skim through some Rust tutorials and finally stumbled upon lifetimes. I can see the need for them in those examples defining multiple scopes, but I can't wrap my head around why they are required in the function longest
in
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
The way I see it, the compiler knows that the lifetime of both strings goes until the end of the program and neither go out of scope before. So, why do we still need to specify the lifetimes explicitly?
I have the feeling that I'm missing something obvious here but I couldn't find a satisfactory explanation.