0

MRE:

enum MRE_Enum {
    variant1,
    variant2,
}

struct MRE_Struct {
    dummy1: Vec<MRE_Enum>,
    dummy2: isize,
}

// Private functions together
impl MRE_Struct {
    fn foo(&mut self) {
        self.dummy2 += 0; // <-- Yeah, MRE...
    }
    fn huh(&mut self) {
        self.dummy2 -= 0; // <-- Yeah, MRE...
    }
    // The only important thing to note here is both the functions modify dummy2 and none, dummy1...
}

// You get a function and you get a function and everybody gets a function... (or public functions together)
impl MRE_Struct {
    pub fn bar(&mut self) {
        for dummy in self.dummy1.iter() {    // <--- immutable (re?)borrow
            match dummy {
                MRE_Enum::variant1 => self.foo(),    // <--- Error... trying to borrow mutably when an immutable borrow exists.
                MRE_Enum::variant2 => self.huh(),    // <--- Error... trying to borrow mutably when an immutable borrow exists.
            } 
        }
    }
}

That's the jist of it.
One way to solve this is to implement the Clone/Copy trait but I don't think that's the idiomatic way to do this.

I looked at Reborrowing of mutable reference, but I do not think that's the issue here.

4
  • You hinted at the solution yourself: split MRE_Struct into two structs. Commented Mar 27 at 16:35
  • A link to the playground: play.rust-lang.org/… Commented Mar 27 at 16:35
  • um, would using a RefCell for dummy2 be overkill? Its literally an isize in the real code too. Commented Mar 27 at 16:36
  • 2
    If it's an isize you can use a Cell. Commented Mar 27 at 16:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.