There are many use cases where something like this comes up:
struct Comp {}
impl Comp {
fn do_some_job(&self, app: &mut App) {
// do some jobs
}
}
struct App {
//... some variables
components: Vec<Comp>,
}
impl App {
fn do_all_jobs(&mut self) {
for c in self.components {
c.do_some_job(self);
}
}
}
But this will throw a borrow checker error. Because self
is already borrowed as immutable in the for
context, but the function do_some_job
needs a mutable reference of App
. I know something like this will work:
#[derive(Clone)]
struct Comp {}
impl Comp {
fn do_some_job(&self, app: &mut App) {
// do some jobs
}
}
struct App {
//... some variables
components: Vec<Comp>,
}
impl App {
fn do_all_jobs(&mut self) {
let comp = self.components.clone();
for c in comp {
c.do_some_job(self);
}
}
}
This can also works:
struct Comp {};
impl Comp {
fn do_some_job(&self, appdata: &mut AppData) {
//...
}
}
struct AppData {
//... some variables
}
struct App {
data: RefCell<AppData>,
comps: Vec<Comp>,
}
impl App {
fn do_all_jobs(&mut self) {
for c in self.comps {
c.do_some_job(self.data.borrow_mut())
}
}
}
But is there any better solution here? Any thoughts greatly appreciated!
New contributor
hapenia lans is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.