4
fn main() {
    let mut foo = 1;

    let mut func = || foo += 1;
    while foo < 5 {
        func();
    }
}
error[E0503]: cannot use `foo` because it was mutably borrowed
 --> src/main.rs:5:11
  |
4 |     let mut func = || foo += 1;
  |                    -- borrow of `foo` occurs here
5 |     while foo < 5 {
  |           ^^^ use of borrowed `foo`

I understand why this isn't working, but I'm looking for a way to bypass the borrow checker somehow. Is there a way to use a closure here? Is there a good alternative besides using a function? I've got a situation where I have to change several variables.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
bertfred
  • 412
  • 4
  • 9

2 Answers2

8

One option you have is to pass a mutable reference to the closure rather than implicitly borrowing it by environment capture:

fn main() {
    let mut foo = 1;

    let func = |foo: &mut i32| *foo += 1;

    while foo < 5 {
       func(&mut foo);
    }
}

playground

Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123
2

No, you cannot do this. While the closure has the mutable borrow, nothing else may access that variable.

Instead...

Runtime mutability XOR aliasing enforcement

You can use a Cell or a RefCell:

use std::cell::Cell;

fn main() {
    let foo = Cell::new(1);

    let func = || foo.set(foo.get() + 1);

    while foo.get() < 5 {
        func();
    }
}

See also:

Let the closure handle everything

You can bake the comparison into the closure:

fn main() {
    let mut foo = 1;

    let mut func = || {
        foo += 1;
        foo < 5
    };

    while func() {}
}

Use a struct

struct Thing(i32);

impl Thing {
    fn do_it(&mut self) {
        self.0 += 1
    }

    fn test_it(&self) -> bool {
        self.0 < 5
    }
}

fn main() {
    let mut foo = Thing(1);

    while foo.test_it() {
        foo.do_it();
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366