Rust mut借书无法关闭

时间:2019-03-10 15:10:56

标签: rust

这是我的代码

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

代码很简单,我不想在闭包中跳过调用l.breakit()。现在,编译器告诉我还有第二个可变借入问题:

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

我使用了RefCell来解决编译问题,但是线程在运行时仍然会出现紧急情况。我应该删除封包中的l.xxx吗?还是有某种方法可以使代码像在C ++或其他语言中运行一样运行?

1 个答案:

答案 0 :(得分:1)

如果f()可以更改test_loop状态,则很自然地将此引用添加到其签名中。这解决了第二次借入问题。

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