Lifetime of string literal

I'm new to rust and reading the book. but I can't understand why does this work?

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

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

the book says the lifetime of longest return value is equal to the lifetime smaller of the a and b.
but what is the lifetime of string2 literal?
why when we use let string2 = String::from("xyz"), then it doesn't work?

'static lifetime of a string literal is infinite, because the literal is hardcoded into the executable and never goes away. Also because it's a lifetime of a shared loan (&), the compiler is able to automatically shorten/unify it with any other lifetime.

Keep in mind that &'static is a special case. The compiler can only shorten lifetimes, and can never extend them. Lifetimes of exclusive loans (&mut) are even less flexible and may not even be possible to shorten automatically.

If you use let string2 = String::from("xyz");, then string2.as_str() will borrow from the string2's String value, which is temporary and destroyed at the end of the scope. string2 = "xyz" borrows from the program's executable, which stays around for as long as the program is running.

4 Likes

If you want to learn more about that "shortening", see Subtyping and Variance in the reference.

2 Likes