Is Rc a good way to work around partial borrow of self?

For the rare case where you cannot refactor your code into refactoring the struct with composition and sub-structs, and if forgetting to put the things back is an issue, you can define your own helper that does this for you:

struct MyStruct {
    things: Vec<Thing>,
    // ...
}

impl MyStruct {
    pub
    fn outer_method (self: &'_ mut Self)
    {
        self.with_things(|this, things| {
            for thing in things.iter() {
                this.inner_method(thing);
            }
        })
    }

    fn inner_method (self: &'_ mut Self, thing: &'_ Thing)
    {}
    
    fn with_things<R> (
        self: &'_ mut Self,
        f: impl FnOnce(&'_ mut Self, &'_ mut Vec<Thing>) -> R,
    ) -> R
    {
        let mut things = ::core::mem::replace(&mut self.things, vec![]);
        let ret = f(self, &mut things);
        self.things = things;
        ret
    }
}
1 Like