Lifetimes: Why Does This Work?

Hi there. I am new to Rust and experimenting with lifetimes. In particular I have been playing with the longest function from Chapter 10 of the book. I think I get the concept, but I would have thought the following should fail to compile. Surprisingly (to me at least) it does not.

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

fn main() {
    let l: &str;
        let s1 = "Hello!";
        let s2 = "Foo";
        l = longest(s1, s2);
    } // both s1 and s2 should fall out of scope here

    println!("Longest string is {:?}", l);

When s1 and s2 fall out of scope, should l not also end its life (or at least not be guaranteed to life after that point. Somehow this works and prints Longest string is "Hello!".

Could somebody please help me understand this? Thank you.

String literals like "Hello" and "Foo" have the special lifetime 'static, which means they will be available for the entire program run. longest then also returns a reference that is valid for the entire program.

1 Like

Ah... yes. Of course. Silly me... Thank you.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.