2

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?

2

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.