doliphin
doliphin

Reputation: 1014

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?

Upvotes: 0

Views: 77

Answers (1)

PitaJ
PitaJ

Reputation: 15094

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.

Upvotes: 1

Related Questions