I am new to Rust and currently learning the lifetime annotation topic. I am still not getting the purpose of lifetime annotation. Consider the below example from Rust book:
fn longest<'a> (x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
/*
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
*/
fn main() {
let x = String::from("abcd");
let y = String::from("xyz");
let z = longest(&x, &y);
println!("{}", z);
}
If I can call the function longest
with valid reference arguments then isn't it obvious that the returned reference will also be valid, which in this case is either &x
or &y
?