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.

2 Answers 2

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

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();
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.