Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment every number in a vector without the error "cannot borrow as mutable more than once at a time"?

This code is supposed to increment each value in a vector by 1:

fn main() {
    let mut v = vec![2, 3, 1, 4, 2, 5];
    let i = v.iter_mut();
    for j in i {
        *j += 1;
        println!("{}", j);
    }
    println!("{:?}", &mut v);
}

It doesn't work because of the borrowing rules of Rust:

error[E0499]: cannot borrow `v` as mutable more than once at a time
 --> src/main.rs:8:27
  |
3 |     let i = v.iter_mut();
  |             - first mutable borrow occurs here
...
8 |     println!("{:?}", &mut v);
  |                           ^ second mutable borrow occurs here
9 | }
  | - first borrow ends here

How can I accomplish this task?

like image 992
saga Avatar asked Oct 15 '25 03:10

saga


1 Answers

Don't store the mutable iterator; use it directly in the loop instead:

fn main() {
    let mut v = vec![2, 3, 1, 4, 2, 5];

    for j in v.iter_mut() { // or for j in &mut v
        *j += 1;
        println!("{}", j);
    }

    println!("{:?}", &v); // note that I dropped mut here; it's not needed
}
like image 131
ljedrz Avatar answered Oct 18 '25 03:10

ljedrz