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?
snake_casefor variables, methods, macros, and fields;UpperCamelCasefor types and enum variants; andSCREAMING_SNAKE_CASEfor statics and constants. UseTestLoopinstead, please. - Shepmaster