Variance of trait object lifetime bound

@Yandros made an interesting observation:

That is, the following program does not compile (it would be unsound if it did!):

trait Trait {}
const _ : () = {
    fn check<'short, 'long : 'short> (
        it: &'short mut Box<dyn Trait + 'long>,
    )
    {
        let _: &'short mut Box<dyn Trait + 'short> = it;
    }
    let _ = check;
};

i.e. , type T1<'x> = &'fixed mut Box<dyn Trait + 'x> is not covariant;

but

trait Trait {}
const _ : () = {
    fn check<'short, 'long : 'short> (
        it: &'short mut (dyn Trait + 'long),
    )
    {
        let _: &'short mut (dyn Trait + 'short) = it;
    }
    let _ = check;
};

does compile fine, meaning that

type T2<'x> = &'fixed mut (dyn Trait + 'x) "is covariant" ??

I was not aware of this distinction, and it is quite surprising to me. I am still trying to figure out the (un)soundness concerns here.

@Yandros you said "it would be unsound if it did" re: covariance of the lifetime on the Boxed trait object; do you have an example of that? Maybe we can finesse that into an exploit for &mut (I'm sure you tried that, but more eyes might help).

Oh sorry, I should have checked first if this was already discussed... it was. Nothing to see here.

2 Likes

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.