fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string2 = String::from("xyzfffssssssssssss");
let string1 = String::from("long string is long");
{ //inner scope 1
let result;
{ // inner scope 2
let str1_ref1= &string1[0..5];
let str2_ref1= &string2[0..5];
result = longest(str1_ref1,str2_ref1);
}
println!("The longest string is {}", result);
}
}
Hi guys, I'm new to Rust, when reading the offical book (Validating References with Lifetimes - The Rust Programming Language). I typed above code which I think it should fail but actually pass. May I get some explanations?
My understanding is that both of lifetime of variable str1_ref1 and str2_ref1 are limited inside inner scope 2. When they are passed to function longest. The returned reference is exactly either str1_ref1 or str2_ref1 with lifetime must be in inner scope2 which is smaller than variable result's lifetime.
Does the rust compiler know that str1_ref1 is essentially referring to string1 which has larger lifetime? I read this chapter several times but got no clue on how this "fact" is revealed by the book.