1
votes

Here is my code

struct test_loop {
    is_break: bool,
}
impl test_loop {
    fn run_forever<F>(&mut self, mut f: F)
    where
        F: FnMut() -> (),
    {
        self.is_break = false;
        loop {
            f();
            if self.is_break {
                break;
            }
        }
    }
    fn breakit(&mut self) {
        self.is_break = true;
    }
}
fn main() {
    let mut l = test_loop { is_break: false };
    let f = || {
        l.breakit();
    };
    l.run_forever(f);
}

The code is simple, and I don't want to skip calling l.breakit() in the closure. Now the compiler tells me there is a second mutable borrow problem:

error[E0499]: cannot borrow `l` as mutable more than once at a time
  --> src/main.rs:26:5
   |
23 |     let f = || {
   |             -- first mutable borrow occurs here
24 |         l.breakit();
   |         - first borrow occurs due to use of `l` in closure
25 |     };
26 |     l.run_forever(f);
   |     ^             - first borrow later used here
   |     |
   |     second mutable borrow occurs here

I used a RefCell to fix the compilation problem, but the thread still panics during run-time. Should I remove the l.xxx in the closure? Or there's some way to make the code act like it is running in C++ or another language?

1
Idiomatic Rust uses snake_case for variables, methods, macros, and fields; UpperCamelCase for types and enum variants; and SCREAMING_SNAKE_CASE for statics and constants. Use TestLoop instead, please. - Shepmaster

1 Answers

1
votes

if f() can change test_loop state, then it's natural to add this reference to its signature. This solves the second borrow problem.

fn run_forever<F>(&mut self, mut f: F)
where
    F: FnMut(&mut Self) -> (), 
{ 
    // call f(self) instead of f()
}

// main
let f = |l: &mut test_loop| {
    l.breakit();
};