Consider these two code examples
struct A {
v: Vec<usize>,
a: usize,
}
impl A {
fn f(&mut self) {
for _ in self.v.iter_mut() {
self.f_mut();
}
}
fn f_mut(&mut self) {
self.a += 1;
}
}
which produces the compile error
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/binaries/main.rs:9:13
|
8 | for _ in self.v.iter_mut() {
| -----------------
| |
| first mutable borrow occurs here
| first borrow later used here
9 | self.f_mut();
| ^^^^ second mutable borrow occurs here
error: aborting due to previous error
whereas this code
struct A {
v: Vec<usize>,
a: usize,
}
impl A {
fn f(&mut self) {
for _ in self.v.iter_mut() {
self.a += 1;
}
}
fn f_mut(&mut self) {
self.a += 1;
}
}
compiles just fine. Obviously these two pieces of code have identical behaviour so I am wondering if there is some way to get Rust to accept the first solution?
In my project I have some quite large for loops which I would like to refactor by splitting the body of the for-loop into separate function calls, but Rust doesn't allow me to do it.
That is, my more complicated code structured as example 2 compiles fine, but refactored into easier digestable functions as example 1 gives me the cannot borrow *self as mutable more than once at a time
error.