I have been experimenting on Rust for quite some time. There is a confusion regarding the lifetimes in Rust.Have a look in the code below:
fn main() {
let string1 = String::from("abcd");
let result;
{
let string2 = "xyzvn";
result = longest(string1.as_str(),string2);
}
println!("The Longest String is {}",result);
}
fn longest<'a>(x: &'a str,y:&'a str) -> &'a str{
if x.len() >y.len(){
x
}
else{
y
}
}
The string2 lifetime ends after the inner scope, and result is defined in the outer scope.When passing result in println!, the compile does not complain, and goes ahead and prints the result. However when I change the string2 to be like:
let string2 = String::from("xyzvd");
The borrow checker will complain. Why is that happening.