Cannot assign to a variable used in a closure because it is borrowed

Viewed 1016

I'm trying to make some sections of my code easier to read by using small helper closures.

fn main() {
    let mut loop_index = 0;

    let get_src_index = || return loop_index % 2;
    let get_dst_index = || return (loop_index + 1) % 2;

    loop_index += 1;
}

There's a few more closures that make use of get_src_index() and get_dst_index(), but they are not important to the problem. The problem is that I can no longer modify loop_index:

error[E0506]: cannot assign to `loop_index` because it is borrowed
 --> src/main.rs:6:5
  |
4 |     let get_src_index = || return loop_index % 2;
  |                         -- borrow of `loop_index` occurs here
5 |     let get_dst_index = || return (loop_index + 1) % 2;
6 |     loop_index += 1;
  |     ^^^^^^^^^^^^^^^ assignment to borrowed `loop_index` occurs here

I don't quite understand why Rust doesn't allow incrementing the loop_index variable. Is there a more "Rusty" way of doing this?

1 Answers
Related