String lifetime

Hi newbie here,

I want to understand more about lifetime
I got this piece of code:

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

i just want to know why the following code compile:

fn main() {
    let x = "hello world";
    let result;
    {
        let y = "foo";
        result = longest(x, y);
    }

    println!("result is '{}'", result);
}

and this one is not:

fn main() {
    let x = String::from("Hello world");
    let result;
    {
        let y = String::from("foo");
        result = longest(&x, &y);
    }

    println!("result is '{}'", result);
}

String literals have a type of &'static str (they are embedded in the executable), so no matter where you write them, they can never be dropped.

In the second example, the String y is dropped at the end of the inner scope, and its allocation is destroyed, so &y would become dangling.

1 Like

When you have two arguments with different lifetimes, the shorter lifetime will win (they'll be unified to the smallest one).

When both x and y had 'static (i.e. infinite) lifetime, the combined one was infinite too.

When y had local lifetime (the inner {}), the combined lifetime was shortened to be always as small as the inner {}.

1 Like

Thx for the explanation..Now i got it

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.