Creating reference of box

Alright… for some practical impact: something like

use std::cell::Cell;

trait A {
    fn smth(&self);
}

struct B {}

impl A for B {
    fn smth(&self) {}
}

fn demonstration<'a: 'b, 'b>(x: Cell<&'a mut B>) -> Cell<&'b mut dyn A> { x }

doesn’t work, even though it would be sound if it did work, AFAICT.

Something like

fn demonstration<'a: 'b, 'b>(x: &'a mut B) -> &'b mut dyn A { x }

does work, probably because it kind-of does two coercions here, which is allowed to be able to happen sometimes (without any further detail beyond “this is not fully supported”) by the reference.

  • T_1 to T_3 where T_1 coerces to T_2 and T_2 coerces to T_3 (transitive case)
    Note that this is not fully supported yet.

If you can chaange the signature of f I got this compiling fine

trait A {
    fn smth(&self);
}
struct B {}
impl A for B {
    fn smth(&self) {}
}
fn f<T: A>(_: &Box<T>) {}
fn main() {
    f(&Box::new(B {}));
}

Well, that's obviously unsound, Cell is invariant over it's parameter.

But Cell is only invariant in order to prevent immutable references to Cell from being covariant. Additional indirection would prevent coercion anyways, so the case of unsize coercion does not need to take this precaution.

1 Like

Oh, yeah. You are right. I really should double check before posting :sweat_smile:

Amazing that is working. The language rules discussion is quite nice though. Thanks everybody for the help !