Lifetimes how come these are not different lifetimes?

fn main()
{
    let str1 = "a".to_string();
    {
        let str2 = "b".to_string();
        longest(&str1, &str2);
    }

    
}

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

How come this code is valid when str1 has a different lifetime compared to str2? Since str2 was defined in an innerscope (inside the main function) so shouldn't the longest function have 'a and 'b?

Lifetimes are not the lifetime of the object. They are the duration in which the object is borrowed. You only borrow the strings for the duration of the line containing the call to longest, and you can certainly borrow both for that duration.

Additionally, given an &'long str, you can turn that into an &'short str. A reference that is valid for a long time is also valid for a short time.

4 Likes