Mutable and immutable methods

I have a problem with calling mutable methods.
How to solve this problem?
I need get &str from HashMap and pass it to next method.


error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/
13 |         let value = self.backend.get(&String::from("vertical")).unwrap().as_str();
   |                     ------------------------------------------- immutable borrow occurs here
14 | 
15 |         self.do_mut_somethings(value);
   |         ^^^^^-----------------^^^^^^^
   |         |    |
   |         |    immutable borrow later used by call
   |         mutable borrow occurs here


Rust's &mut self methods aren't just mutable, they're exclusive with very absolute definition of the exclusivity. It means that nothing borrowed from &mut self can be accessible anywhere while this method is called. In your case value exists, so you're unable to guarantee that self, and all of its fields and values of these fields, are exclusively accessible only through self and nothing else.

You have three options:

  1. Use a shared reference for mutation. &self does not mean immutable. It's perfectly fine to mutate & through interior mutability, like RefCell, Mutex or Atomic*.

  2. Use a copy of value, so that it's no longer temporarily borrowed from self, e.g. let value = value.clone(); self.do_mut_something(&value);

  3. Store backend in a different struct, so that exclusively borrowing &mut self doesn't claim exclusive access to backend too.

1 Like

Must read: Baby Steps