rustlifetimeborrow-checker

Why does this rust borrow checker doesn't reject this code?


The following doesn't compile as I expected, as y is dropped before r.

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

fn main() {
    let x = String::from("xyz");
    let r;
    {
        let y = String::from("abc");
        r = longest(x.as_str(), y.as_str());
    }   // y is dropped

    println!("The longest string is {r}");
}

However the following is accepted by the borrow checker, why?

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

fn main() {
    let x = String::from("xyz");
    let r;
    {
        let y = "abcd";
        r = longest(&x, y);
    } // y should be dropped here right?

    println!("The longest string is {r}");
}

Solution

  • {
        let y = "abcd";
        r = longest(&x, y);
    } // y should be dropped here right?
    

    y in this case is a literal, it has static lifetime since it's always in memory as mapped by the OS loader.