How to idiomatically iterate over a mutable vector while examining other elements

Viewed 91

I want to write code like this:

let mut v: Vec<Object> = Vec::new();
for e in v.iter_mut() {
  if e.some_predicate() {
    e.val = v.iter().filter(|o| o.some_predicate()).count();
  }
}

This doesn't work because the for loop takes a mutable borrow, and then the iter tries to do an immutable borrow. I understand why the borrow checker doesn't like the specific types produced, but the operation I'm trying to do seems safe, and if I rewrite it to use indices it works fine:

let mut v: Vec<Object> = Vec::new();
for i in 0..v.len() {
  if v[i].some_predicate() {
    v[i].val = v.iter().filter(|o| o.some_predicate()).count();
  }
}

What is the idiomatic way to do this in rust?

0 Answers
Related