Variable lifetime misunderstanding

The code:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
    } else {

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

The compiler isn’t wrong. Anything you store in a variable has to live at least as long as the variable itself. Variables are destroyed in reverse lexical order at the end of their defining scope. Thus, if the compiler allowed this, result would contain a pointer to one of two strings, both of which are destroyed before itself.

1 Like

@DanielKeep Thank you for that clear and concise answer. I have changed my title to better suit my issue.