The code:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
{
let result;
let string1 = String::from("long string is long");
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
println!("The longest string is {}", result);
}
}
Returns that both ‘string1’ and ‘string2’ do not live long enough; however, if you remove the line “let result;” and add “let” to the beginning of the variable assignment of result so that it becomes let result = longest(string1.as_str(), string2.as_str());
the code runs just fine. I believe the two code examples should be identical but the compiler says otherwise.
In learning Rust I can’t seem to understand why this error occurs and hopefully somebody could enlighten me. The code is a modified version of the “Lifetime Annotations in Function Signatures” section in Chapter 10.3 of the book.
The faulty code can be run through rust playground
https://play.rust-lang.org/?gist=7398d397a492ca3835cfcd02110589e6&version=stable&mode=debug