Immutable Borrow?

`Hi everyone why is the code below showing the error

cannot borrow "answers" as immutable because it is also borrowed as mutable

fn get_answers(limit: usize) -> Vec<u32>  { 
      let mut answers: Vec<u32> = (0..=limit as u32).collect();

      for i in 2..answers.len() as u32 {
            if answers[i as usize] == i {
                  for vj in answers.iter_mut().skip(i as usize).step_by(i as usize) {
                        *vj -= *vj / i;
                  }
            }
      }

      for (i, vi) in answers.iter_mut().enumerate().skip(1) {
           *vi += answers[i - 1];
      }

      answers
}

You can't modify a vector while iterating through that vector. Consider doing this instead:

let mut last = answers[0];
for vi in answers.iter_mut().skip(1) {
    *vi += last;
    last = *vi;
}

or this:

for i in 1..answers.len() {
    answers[i] += answers[i - 1];
}

Also please use three backtics for code blocks:

```
// your code here
```
for i in 1..answers.len() {
    answers[i] += answers[i - 1];
}

Isn't that same with iterating? What's the difference? Sorry for the naive question.

The difference is that the iter_mut iterator is an object that contains a reference into the vector, whereas that loop just produces some integers.

When you use the integers, the compiler inserts a check that the integer is less than the length every time you index into the vector, whereas the iterator does not have to perform this check in every iteration: The compiler ensures that nothing else can access the vector while the iterator exists, so it knows that the length cannot change, and therefore it knows that this length check is redundant.

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