Cannot borrow as mutable more than once when calling &'a mut self method

The x method takes &'a mut self, so it must borrow the A struct for the same lifetime as the references stored inside of the struct. This must be at least as long as the struct's own lifetime, since you can't store short-lived references in a long-lived struct:

fn x(&'a mut self)

As you've seen, taking an unique reference to a struct and storing it within that struct effectively locks that struct for its entire lifetime, preventing any other use of the struct, ever.

One way around this is to use a type like RefCell so that x can take a shared reference instead of a unique reference:

use std::cell::RefCell;

struct A<'a> {
    b: &'a mut B,
    v: RefCell<Vec<&'a B>>,
}

impl<'a> A<'a> {
    fn x(&'a self) {
        self.v.borrow_mut().push(self.b);
    }
}
1 Like