Cannot borrow `*self.element` as mutable more than once

I've used rust for a while and i've seen this error many times and still can't figure out the issue. here is where it occurred: self.element.update(self, key::read_key());

this would be perfectly safe imo idk why the borrow checker is buggin.

error[E0499]: cannot borrow `*self.element` as mutable more than once at a time
  --> src/lib.rs:84:13
   |
84 |             self.element.update(self, key::read_key());
   |             ^^^^^^^^^^^^^------^----^^^^^^^^^^^^^^^^^^
   |             |            |      |
   |             |            |      first mutable borrow occurs here
   |             |            first borrow later used by call
   |             second mutable borrow occurs here

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/lib.rs:84:33
   |
84 |             self.element.update(self, key::read_key());
   |             ------------ ------ ^^^^ second mutable borrow occurs here
   |             |            |
   |             |            first borrow later used by call
   |             first mutable borrow occurs here

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

In the update method, the &mut self and first_param.element would alias each other, which is UB.

(Based purely on the error since you have shared no code.)

1 Like

here is the whole function:

pub fn run(&mut self) {
        // Initialize
        utils::hide_cursor();
        utils::clear();
        let mut stdout = std::io::stdout();
        stdout
            .execute(crossterm::terminal::EnterAlternateScreen)
            .unwrap();
        crossterm::terminal::enable_raw_mode().unwrap();

        loop {
            self.element.update(self, key::read_key());
        }
    }

here is the app struct

pub struct App {
    element: Box<dyn Element>,
}

and Element:

pub trait Element: std::fmt::Debug {
    fn update(&mut self, _app: &mut App, _k: crate::key::Key) -> UpdateResponse {
        UpdateResponse::None
    }
}

App has some functions that update needs to access

Yep, that confirms it. You'll have to factor things out so that you don't need to pass both self.element (as the receiver) and self to Element::update in run.

See this article for some potential workarounds.

https://smallcultfollowing.com/babysteps/blog/2018/11/01/after-nll-interprocedural-conflicts/

2 Likes