In Rust book (https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html), this code is used as example (paraphrased):
fn main() {
let string1 = String::from("long string is long");
{
let string2 = String::from("xyz");
let result = longest(string1.as_str(), string2.as_str()); // line 5
println!("The longest string is {}", result); // line 6
}
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
I am confused why this code compiles at all.
Regarding the longest
function, the book says, "the generic lifetime 'a will get the concrete lifetime that is equal to the smaller of the lifetimes of x and y".
The book then talked as if string1.as_str()
and string2.as_str()
live as long as string1
and string2
respectively. But why would they? These two references were not used after line 5, and by line 6, they should have been dead. Why there wasn't an error at line 6 for using result when it is no longer live?
One could say that presence of result
somehow extends the input lifetimes, but wouldn't that contradict the notion that "output lifetime is the intersection of input lifetimes"?
Where do I get it wrong?