`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
}
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.