I have the structs Foo
and Bar
. Foo
contains an array of Bar
and a private method to operate on Bar
:
pub struct Bar;
pub struct Foo {
bars: [Bar; 10],
}
impl Foo {
pub fn process_all(&mut self) {
for bar in self.bars.iter_mut() {
self.process_single(bar);
}
}
fn process_single(&mut self, bar: &mut Bar) {
// ...
}
}
This won't work because both self
and one of its contained bars can't be borrowed at the same time.
error[E0499]: cannot borrow `*self` as mutable more than once at a time
One way of solving this in my case is an Option
. I then have the ability to take ownership of the array in the function and then later giving it back to the struct after the process is done:
pub struct Bar;
pub struct Foo {
bars: Option<[Bar; 10]>,
}
impl Foo {
pub fn process_all(&mut self) {
let bars = self.bars.take().unwrap();
for bar in bars {
self.process_single(bar);
}
self.bars = Some(bars);
}
fn process_single(&mut self, bar: &mut Bar) {
// ...
}
}
This feels very hacky; is there a better way?