How to swap contents of two indices of a Vec inside a loop?

Viewed 167

I'm trying to swap the elements inside a loop.

fn foo(nums: &mut Vec<i32>) {
  let mut i: usize = 0;
  for (j, n) in nums.iter_mut().enumerate() {
    if n != &0 {
      // swap nums[i] and nums[j];
      i = i + 1;
    }
  }
}

But I keep getting the same error (along cannot borrow mutable nums multiple times). What am I doing wrong?

1 Answers

Maybe this is not exactly what you want but it may help.

fn main() {
    let mut vec = vec![1, 0, 3, 4];
    let mut i = 0;

    for j in 0..vec.len() {
        if vec[j] != 0 {
            vec.swap(i, j);
            i = i + 1;
        }
    }

    println!("{:?}", vec);
}

Rust Playground

Related