Issue accessing a struct member while traversing through another member

I'm trying to access a member of a struct while another member, a Vector, is being traversed and mutated using the for_each function. I've got the following error -

cannot borrow self as immutable because it is also borrowed as mutable

and am not able to figure out a work around. Here's my simplified source code - Rust Playground.

The relevant code is at line 23.

I know for sure that I am not going to mutate the value member of the struct instance when trying to traverse through vector. Is there a way of letting the compiler know this so I can immutably access value?

Any help would be much appreciated!

It's because the closure passed to the .for_each() borrows the self reference itself and access the field value within it. There're two easy fixes for this specific code.

First, you can separate the field before the borrowing is passed to the closure.

let value = self.value;
self.vector.iter_mut().for_each(|x| {
    x.hello += value;
});

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7c8dd22ed0a4ef4282b9ac3a8a0747fb

Or you can replace the .for_each() call with the for loop to eliminate the closure which makes the borrow issue.

for x in &mut self.vector {
    x.hello += self.value;
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=96754e6f6f95b80398fb75b3251f7c2a

2 Likes

I'll use the first solution you offered. Thank you.

As an after thought, wouldn't it be useful to access a particular member of a struct as mutable and the others as not?

In my piece of code, self.vector.iter_mut() makes it pretty apparent that only the vector member is going to be mutated. Why then does the compiler have to assume a possible mutation in the value member?

Because the closure body refers the name self, the closure value borrows the variable self. But it fails as a part of it - self.vector - is already borrowed uniquely(&mut).