So I’m trying to work with a stuct that contains a series of Vecs, some of which I iterate over (in this context immutably), but while I do this I need to modify another Vec included in the struct.
A lot of people have been talking about the “struct of vecs” pattern and how it is used in “data driven programming.” Basically I’m trying to do that.
My iterators are complicated. That said, they only work over the immutable vecs. (At least immutable in this function. The get mutated in other functions.)
Here is a super-simplified version of what I want to do. I understand why it fails, but there must be some nice way to work with structs like this. How do I make this work?
(My actual iterator is much more complex than this. I cannot simplify it.)
#[derive(Copy, Clone)]
struct Mary;
struct Fred {
a: Vec<Mary>,
b: Vec<Mary>,
}
impl Fred {
fn mary_iter(&self) -> MaryIter {
MaryIter {
mary_slice: &self.a,
idx: 0,
}
}
fn do_thing(&mut self) {
for i in self.mary_iter() {
self.b.push(i);
}
}
}
struct MaryIter<'a> {
mary_slice: &'a [Mary],
idx: usize,
}
impl<'a> Iterator for MaryIter<'a> {
type Item = Mary;
fn next(&mut self) -> Option<Mary> {
if self.idx == self.mary_slice.len() {
None
} else {
let result = self.mary_slice[self.idx];
self.idx += 1;
Some(result)
}
}
}
fn main() {
}
Errors:
Compiling playground v0.0.1 (file:///playground)
error[E0502]: cannot borrow `self.b` as mutable because `*self` is also borrowed as immutable
--> src/main.rs:21:13
|
20 | for i in self.mary_iter() {
| ---- - immutable borrow ends here
| |
| immutable borrow occurs here
21 | self.b.push(i);
| ^^^^^^ mutable borrow occurs here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.