Why the life time is equal?

Hello everyone,
I have the following code and it compiles, showing the lifetime of b, e is same.
Can't figure out why.
Anybody help to make an explaination?

#[cfg(all())]
fn main() {
    fn equal<'a, 'b, T>(s1: &'a mut T, s2: &'b mut T)
    where
        'a: 'b,
        'b: 'a,
        T: 'a,
    {
    }

    let mut a = "1".to_owned();
    {
        let mut b: &mut String = &mut a;

        {
            let mut d = "2".to_owned();
            {
                let mut e: &mut String = &mut d;
                equal(b, e);
            }
        }

        b;
    }
}

I think the reason is subtyping, i.e. you can always pass longer-living references (unless there is invariance enforced).

Yes, it is invariant, notice s1: &'a mut T, s2: &'b mut T

No, &'a mut T is covariant in 'a but invariant in T. (I made that mistake previously too.)

5 Likes

Sorry, I forget the invariant rule

The code will fail to compile if you work with &mut &'lt T:

fn main() {
    fn equal<'a, 'b, T>(s1: &mut &'a T, s2: &mut &'b T)
    where
        'a: 'b,
        'b: 'a,
        T: 'a,
    {
    }

    let a = "1".to_owned();
    {
        let b: &mut &String = &mut &a;
        {
            let d = "2".to_owned();
            {
                let e: &mut &String = &mut &d;
                equal(b, e);
            }
        }
        b;
    }
}

(Playground)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.