rust - Rust mut 借用关闭失败
问题描述
这是我的代码
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
我用 aRefCell
来修复编译问题,但线程在运行时仍然会出现恐慌。我应该l.xxx
在关闭中删除吗?或者有什么方法可以让代码表现得像在 C++ 或其他语言中运行一样?
解决方案
如果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();
};
推荐阅读
- php - How do I set up a deep relation in Eloquent?
- powershell - PS7.1 - 你如何使用带有自定义函数的流水线链接?
- parsing - Antlr Matlab 语法词法冲突
- python-3.x - How to define a function that checks each column of 'object' dtype and gets those columns which can be converted to datetime format
- amazon-web-services - 通过 AWS S3 SDK 访问 Google Cloud Storage 遇到带有特殊字符的文件的 403 错误
- r - lmer or binomial GLMM
- ruby-on-rails - 调用中的 RSpec 未定义方法“每个”
- discord.js - Creating an invite in a GuildCreate event
- flutter - 在容器下方显示列表视图时出错
- angular - 显示更多和显示更少的角度