1

Suppose I have the following simplified code

struct SomeStruct;

impl SomeStruct {
    fn func(&self, input: usize) {
    }

    fn func_mut(&mut self) -> usize {
        0
    }

    fn do_some_work(&mut self) {
        self.func(self.func_mut());
    }
 }

fn main() {
    let mut s = SomeStruct {};
    s.do_some_work();
}

Attempt to compile it fails with


error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/main.rs:12:19
   |
12 |         self.func(self.func_mut());
   |         ----------^^^^^^^^^^^^^^^-
   |         |    |    |
   |         |    |    mutable borrow occurs here
   |         |    immutable borrow later used by call
   |         immutable borrow occurs here

For more information about this error, try `rustc --explain E0502`.

If I rewrite do_some_work body as

    fn do_some_work(&mut self) {
        let result = self.func_mut();
        self.func(result);
    }

rustc compiles it successfully.

Initially I thought that rustc would expand self.func(self.func_mut()) to something similar with temp variables but obviously this is not the case.

Now I would really like to understand how the compiler actually treats such pieces of code and why it can not compile it.

S.S.J
  • 353
  • 1
  • 7

0 Answers0