The following function is a typical example given when explaining lifetimes.
fn longest_string<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() >= s2.len() {
s1
} else {
s2
}
}
From the Rust documentation (https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) we can read the following: "The concrete lifetime that is substituted for ‘a is the part of the scope of s1 that overlaps with the scope of s2. In other words, the generic lifetime ‘a will get the concrete lifetime that is equal to the smaller of the lifetimes of s1 and s2."
Given the above description, how is it that the following example compiles??
fn main() {
let res;
let s1 = "Hello";
{
let s2 = "World!!";
res = longest_string(s1, s2);
println!("{} is longer", res);
}
println!("Finished with {} and with {}", s1, res);
// lifetime of 'res' should be tied to s2, and thus have expired ??
}
It seems to me that the lifetime of ‘res’ should have ended when s2 went out of scope, and caused a compiler error on the last line, but that didn’t happen. This compiles (and runs) without errors.
Can someone explain why?
>Solution :
Your example works, because strings literals in rust have type &'static str. So even that s2 is in separate block it has the same lifetime as s1. If you instead create String inside inner block and passed it’s reference you would get en error that you expected.