Skip to content

Conversation

@Zantier
Copy link

@Zantier Zantier commented Apr 28, 2022

The borrow checker must check that the returned reference doesn't
outlive any of the parameters (with the same lifetime annotation), so
reword to "will live at most as long".

The borrow checker must check that the returned reference doesn't
outlive any of the parameters (with the same lifetime annotation), so
reword to "will live at most as long".
@carols10cents
Copy link
Member

No, this is correct as-is. Please see the extensive discussion on #1875

@Zantier
Copy link
Author

Zantier commented Apr 29, 2022

Ok, thanks! I've spent some time thinking, and I think I finally understand it, so I'll just leave a quick explanation here in case it helps anybody.

Let's call the string slice returned from the function ret.

As the book says:

The function signature tells Rust that ret will live at least as long as lifetime 'a.

But Rust does not know whether ret will live any longer than 'a, and so to be safe, ret is only valid for the lifetime 'a i.e. Rust will only let you use ret AT MOST up until 'a dies.


For example, the following code does not compile:

fn main() {
    let string1 = String::from("abcd");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
        println!("The longest string is {}", result);
    }
    // Compile error
    println!("The longest string is {}", result);
}

fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str {
    "hi"
}

Here, we return "hi" from longest(), which has a lifetime of 'static, which satisfies:

... ret will live at least as long as lifetime 'a

Then in main(), Rust knows that result will live at least as long as 'a, but doesn't know that result is 'static and will in fact live forever, so Rust only lets you use result AT MOST up until 'a dies, which is at the end of the inner scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants