I have a hard time expressing in Rust code my intention to iterate a field and mutate fields which are not the iterator.
I'll use minimal code to express my intention
struct Foo {
field: usize,
some_vec: Vec<usize>
}
impl Foo {
fn mut_with_item(&mut self, item: usize) {
self.field = self.field + item
}
fn mut_per_item(&mut self){
for &item in &self.some_vec {
self.mut_with_item(item)
}
}
}
results in the error:
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/lib.rs:13:13
|
12 | for &item in &self.some_vec {
| --------------
| |
| immutable borrow occurs here
| immutable borrow later used here
13 | self.mut_with_item(item)
| ^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
and I understand why I get that error, I iterate over data owned by self while mutating self. However - I am confident that the way I mutate self doesn't mutate that particular field.
Let's say that cloning is out of the question, how do I best express my confidence to Rust?