How to call mutable member function in a for loop?

Hi everyone,

I have the following example code:

struct Data {
    data: Vec<PathBuf>
}

impl Data {
    pub fn some_function(&mut self) {
        for item in self.data.iter_mut() {
            self.do_something(item);
        }
    }

    fn do_something(&mut self, _item: &Path) {
        // Do stuff
    }
}

Which results in the following compiler error:

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:11:13
   |
10 |         for item in self.data.iter_mut() {
   |                     --------------------
   |                     |
   |                     first mutable borrow occurs here
   |                     first borrow later used here
11 |             self.do_something(item);
   |             ^^^^ second mutable borrow occurs here

I understand the problem and where the error lies. I'm just not sure how best to fix it. There will be a general structural error in the code here. But coming from C++, this is a relatively common situation.

I could clone the vector before the for loop let mut temp = self.data.clone(), but with large vecs this is not really optimal in terms of performance, especially if this is done every frame.

How can the code be improved?
Thanks in advance! :slight_smile:

1 Like

Here's an article about it that explores various workarounds.

Additionally, like in this related article, you may be able to temporarily move the data out of self (without cloning).

    pub fn some_function(&mut self) {
        let mut data = std::mem::take(&mut self.data);
        for item in data.iter_mut() {
            self.do_something(item);
        }
        self.data = data;
    }
7 Likes

These are the resources I needed. Thanks for the quick reply!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.