Hi all!
I am studying the lifetime functionality in Rust following the 'The Rust Programming Language' book. In the chapter 10 the lifetime is explained and some examples are given. Then the writer suggests try to image another scenarios and see what happens and this is how I came to the behavior bellow:
//The function
fn longest<'a>(str1: &'a str, str2: &'a str) -> &'a str {
if str1.len() > str2.len(){
str1
} else {
str2
}
}
fn main() {
let str1 = String::from("Holy teeeest!");
let result;
{
let another_str = "Inner str from scope.";
result = longest(str1.as_str(), another_str);
}
println!("The longest str is {}", result);
}
The code above compiles and run, but the code bellow don't.
fn main() {
let str1 = String::from("Holy test again!");
let result;
{
let another_str = String::from("Inner str from scope.").as_str();
result = longest(str1.as_str(), another_str);
}
println!("The longest str is {}", result);
}
The only diference from the first block to the second is the declaration of the another_str
in the inner scope and the compiler shows the following message:
error[E0597]: `another_str` does not live long enough
--> src/main.rs:16:41
|
16 | result = longest(str1.as_str(), another_str.as_str());
| ^^^^^^^^^^^ borrowed value does not live long enough
17 | }
| - `another_str` dropped here while still borrowed
18 | println!("The longest str is {}", result);
| ------ borrow later used here
error: aborting due to previous error
Can someone help me understand this behavior, please?
Thank you!