简体   繁体   中英

Rust: allow upgrade of immutable reference to mutable reference, if no other references exist

struct ImmutRef<'a, T>(&'a T);

struct MutRef<'a, T>(&'a mut T);

struct Foo;

impl Foo {
    fn upgrade_ref(&mut self, _: ImmutRef<Self>) -> MutRef<Self> {
        MutRef(self)
    }
}

let mut foo = Foo;
let immut_ref = ImmutRef(&foo);
let mut_ref = foo.upgrade_ref(immut_ref);

This code does not compile.

error[E0502]: cannot borrow `foo` as mutable because it is also borrowed as immutable
  --> src/main.rs:63:16
   |
62 |     let immut_ref = ImmutRef(&foo);
   |                              ---- immutable borrow occurs here
63 |     let mut_ref = foo.upgrade_ref(immut_ref);
   |                   ^^^^-----------^^^^^^^^^^^
   |                   |   |
   |                   |   immutable borrow later used by call
   |                   mutable borrow occurs here

I get the above error instead.

Yes, immut_ref borrows foo immutably, however it is moved when we call foo.upgrade_ref . Therefore, there are no longer any references to foo and I should be able to get a mutable reference to foo .

Why does this not compile?

upgrade_ref takes &mut self and ImmutRef<Self> . You're trying to pass it &mut foo and &foo at the same time. But an immutable reference and mutable reference can't exist at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM