Problematic pattern I've encountered a few times now...

186 points kosmology

Hi everyone,

I've encountered this pattern a few times now and I've always had to painfully refactor to get around it, but I'm wondering if there's a simpler way. Essentially, I want to iterate over a Vec struct member and call a mutable member function on each item. Here's a simplified code snippet that highlights the problem:

struct Foo {
    items: Vec<u32>,
}

impl Foo {
    fn run_all(&mut self) {
        for item in &self.items {
            self.run_one(item);
        }
    }
    
    fn run_one(&mut self, item: &u32) {
        // ...
    }
}

The issue is an immutable borrow occurs at &self.items, and a mutable borrow occurs at self.run_one(item). I'm wondering if this is a pattern others have encountered as well and how people fix/avoid it.