![](/img/trans.png)
[英]Cannot borrow as mutable in a loop when calling a closure that borrows as immutable?
[英]“Cannot borrow immutable content as mutable” when moving a closure into a thread
在Rust中,我想指定在发生有趣的事情时由工作线程调用的回调(例如,闭包)。 回调的正确类型签名是什么?
这是我正在尝试做的一个例子:
use std::thread;
fn spawner(f: Box<FnMut()->()+Send>) -> thread::JoinHandle<()> {
thread::spawn(move || {
f();
})
}
fn main() {
let cb = || {
println!("callback");
};
spawner(Box::new(cb)).join().unwrap();
}
src/main.rs:5:9: 5:10 error: cannot borrow immutable `Box` content `*f` as mutable src/main.rs:5 f();
Rust中的可变性是继承的:因为保存该框的变量f
是不可变的,所以该框的内容也是不可变的。 不变的FnMut
闭包不能被调用( FnMut
需要能够改变其环境的能力)。
解决方案:使变量f
可变:
fn spawner(mut f: Box<FnMut()->()+Send>) -> thread::JoinHandle<()>
Rust编译器不允许您将不可变参数f
移动到闭包中。 将其更改为可变的(在变量之前添加mut
),编译器将停止抱怨,您将获得所需的行为。
use std::thread;
fn spawner(mut f: Box<FnMut()->()+Send>) -> thread::JoinHandle<()> {
thread::spawn(move || {
f();
})
}
fn main() {
let cb = || {
println!("callback");
};
spawner(Box::new(cb)).join().unwrap();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.