Question about lifetime

fn main() -> () {
    let result;
    let x = "hello";
    {
        let y = "everyone";             
        result = longest(x, y);  
    } //lifetime of result should be until here, y is dropped
    println!("{}", result)                                  
}

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

I don't understand how can this compile? 'a should be smaller of the lifetime of first and second, in this case the lifetime of y. In this case there is a hanging reference isn't it? y is dropped. reference of y is saved in result. and result is being printed after y is dropped.

I am using rustc 1.42.0. Have the compiler become more clever? How does it decide that this can be compiled?

The lifetimes of "hello" and "everyone" are 'static. i.e. they have the same lifetime as the program.

This code gives you the result you expected by making a local copy of the strings: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a331cbd1e6fb8319b09c148acf8fab89

1 Like

Ahhh i see it now. Because x and y are string literals so they have static lifetime.

fn main() -> () {
    let result;
    let x = String::from("hello");
    {
        let y = String::from("everyone");             
        result = longest(&x, &y);  
    } 
    println!("{}", result)                                  
}

x and y need to be String and references have to be actual reference with non static lifetime.

1 Like

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