[英]Cannot borrow captured outer variable in an Fn closure when using a closure with an Rc
use std::rc::Rc;
fn f1(cb: Box<Fn(i32) -> i32>) {
let res = cb(15);
println!("res {}", res);
}
fn main() {
let mut v2 = Rc::new(5_i32);
// 1
// f1(Box::new(move |x: i32| *v2 + x));
// 2
f1(Box::new(move |x: i32| {
let tmp = *v2;
*Rc::get_mut(&mut v2).unwrap() = tmp + 1;
x + *v2
}));
}
The code referenced as "1", if uncommented, compiles and runs just fine, but the code referenced as "2" does not compile, failing with the message: 引用为“1”的代码,如果取消注释,编译并运行得很好,但引用为“2”的代码无法编译,失败并显示以下消息:
error[E0596]: cannot borrow `v2` as mutable, as it is a captured variable in a `Fn` closure
How can I fix this, if I want keep the code structure as it is? 如果我想保持代码结构,我该如何解决这个问题呢?
In my real code, I want connect two traits. 在我的真实代码中,我想要连接两个特征。 One of them will call a callback on event, and the other has a function to handle the callback:
其中一个将调用事件的回调,另一个具有处理回调的函数:
trait Foo {
fn add_callback(&mut self, cb: Box<Fn(i32)>);
}
trait Boo {
fn on_new_data(&mut self, data: i32);
}
I want to create a trait object with Boo
, wrap it with Rc
, and pass it to Foo::add_callback
in the form of |x:i32| Rc::get_mut(&mut boo).unwrap().on_new_data(x)
我想用
Boo
创建一个trait对象,用Rc
包装它,并以|x:i32| Rc::get_mut(&mut boo).unwrap().on_new_data(x)
的形式传递给Foo::add_callback
。 |x:i32| Rc::get_mut(&mut boo).unwrap().on_new_data(x)
The entire error message is mostly helpful: 整个错误消息最有用:
error[E0596]: cannot borrow `v2` as mutable, as it is a captured variable in a `Fn` closure
--> src/main.rs:17:19
|
17 | *Rc::get_mut(&mut v2).unwrap() = tmp + 1;
| ^^^^^^^ cannot borrow as mutable
|
help: consider changing this to accept closures that implement `FnMut`
--> src/main.rs:15:17
|
15 | f1(Box::new(move |x: i32| {
| _________________^
16 | | let tmp = *v2;
17 | | *Rc::get_mut(&mut v2).unwrap() = tmp + 1;
18 | | x + *v2
19 | | }));
| |_____^
Changing f1
to accept a FnMut
and making the variable mutable allows the code to compile: 更改
f1
以接受FnMut
并使变量可变允许代码编译:
fn f1(mut cb: Box<FnMut(i32) -> i32>) {
This is needed in order to mutate the captured variable v2
, required by the &mut v2
argument to Rc::get_mut
. 这是为了将
&mut v2
参数所需的捕获变量v2
变为Rc::get_mut
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.