Correct way of using for loop on struct with Iterator trait

Hello,

I was wondering if anyone could help me with following error:

error[E0382]: borrow of moved value: `simple_intcode`
  --> src/main.rs:66:5
   |
58 |   let mut simple_intcode = SimpleIntcode { intcodes: single_integers, step_size: 4, last_index: 0};
   |       ------------------ move occurs because `simple_intcode` has type `SimpleIntcode`, which does not implement the `Copy` trait
...
61 |   for (act, x1, x2, pos) in simple_intcode {
   |                             --------------
   |                             |
   |                             value moved here
   |                             help: consider borrowing to avoid moving into the for loop: `&simple_intcode`
...
66 |     simple_intcode.add_operation(x1 as usize, x2 as usize, pos as usize);
   |     ^^^^^^^^^^^^^^ value borrowed here after move

which occurs for following code:

#[derive(Debug)]
struct SimpleIntcode { intcodes: Vec<i32>, step_size: usize, last_index: usize }


impl Iterator for SimpleIntcode {
  type Item = (i32, i32, i32, i32);
  
  fn next(&mut self) -> Option<Self::Item> {
    let curr_index: usize = self.last_index;
    self.last_index += self.step_size;
    
    if self.intcodes.len() - curr_index < self.step_size {
      return None;
    }
    
    Some((self.intcodes[curr_index], self.intcodes[curr_index + 1], self.intcodes[curr_index + 2], self.intcodes[curr_index + 3]))
  }
}

impl SimpleIntcode {
  fn add_operation(&mut self, a_pos: usize, b_pos: usize, sum_pos: usize) -> () {
    let sum = self.intcodes[a_pos] + self.intcodes[b_pos];
    if sum_pos < self.intcodes.len(){
      self.intcodes[sum_pos] = sum;
    }
  }
}

and then

  for (act, x1, x2, pos) in simple_intcode {
    simple_intcode.add_operation(x1 as usize, x2 as usize, pos as usize);  
  }

Full snippet is available here

I understand that whenever next iterations of for loop are invoked I am 'loosing' ownership of simple_intcode, but how can I achieve following scenario?

Thanks for all your answers.

Regards

If you intend to keep ownership of the iterator after the loop or modify it during the loop, you can use a while let loop.

while let Some(item) = simple_intcode.next() {
    ...
}

Typically we use play.rust-lang.org for snippets here as that site allows running the code in the browser.

Thank you! It worked fine:)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.