How to `&mut self` method in itertor vec

struct A {
    fp: u32,
    section: Vec<B>
}

struct B{}

impl A {
    pub fn instance(&mut self) {
        self.fp = 0;

        for item in self.section.iter() {
            self.run(&item);
        }
    }
    pub fn run(&mut self, _code: &B) {
        // ...
        self.fp = 1;
    }
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/lib.rs:13:13
   |
12 |         for item in self.section.iter() {
   |                     -------------------
   |                     |
   |                     immutable borrow occurs here
   |                     immutable borrow later used here
13 |             self.run(&item);
   |             ^^^^^^^^^^^^^^^ mutable borrow occurs here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` (lib) due to previous error

impl A {
    pub fn instance(&mut self) {
        self.fp = 0;
        for item in self.section.iter() {
            run(&mut self.fp, &item);
        }
    }
    pub fn run(&mut self, _code: &B) {
        run(&mut self.fp, _code);
    }
}

fn run(fp: &mut u32, _code: &B) {
    // ...
    *fp = 1;
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f059b0fba98dda2abfa87f7284f90163

1 Like

Alternatively if run never cares about section directly:

    pub fn instance(&mut self) {
        self.fp = 0;

        let section = std::mem::take(&mut self.section);
        for item in section.iter() {
            self.run(&item);
        }
        self.section = section;
    }

Related reading:

2 Likes

in my code , when code run to instance, section will be readonly

But do you need to read it? If not, something like I posted could work.

If so, a view struct would work.

1 Like

i will read it later, your code resolve my problme

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.