Why does Box work, but Rc not compile?

Minimal failure case:

pub struct Foo<'a> {
    r: &'a mut i32,
}

#[test]
fn compiles() {
    let mut x = 20;
    let r: &mut i32 = &mut x;
    let t = Box::new(Foo { r: r });
    *t.r = 23;
}

#[test]
fn fails_to_compile() {
    let mut x = 20;
    let r: &mut i32 = &mut x;
    let t = Rc::new(Foo { r: r });
    *t.r = 23;
}

The reason i expect this to work is that Foo::r is a &mut i32.

But when you do *t.r = ... in the Rc case you're accessing that exclusive reference through a shared reference, which downgrades the access you can get from it to shared one.

4 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.