【发布时间】:2021-06-27 21:05:02
【问题描述】:
我想在实现克隆的结构中存储一个闭包,所以我编写了这样的代码:
use std::rc::Rc;
type Closure = Box<dyn Fn() -> ()>;
#[derive(Clone)]
struct A {
closure: Option<Rc<Closure>>,
}
impl A {
pub fn new() -> A {
A { closure: None }
}
pub fn closure(&self) -> Option<Rc<Closure>> {
self.closure.clone()
}
pub fn set_closure(&mut self, closure: Closure) -> &mut Self {
self.closure = Some(Rc::new(closure));
self
}
}
fn main() {
let mut a: A = A::new();
a.set_closure(Box::new(|| -> () { println!("Works fine!") }));
(a.closure().unwrap())();
}
现在我想通过借用当前范围的变量来测试这段代码。在 main 函数中保留一个引用很重要,因为我需要在之后使用它。 我编码:
use std::cell::RefCell;
fn main() {
let mut a: A = A::new();
let value: Rc<RefCell<i8>> = Rc::new(RefCell::new(0));
println!("Value = {}", value.borrow());
a.set_closure(Box::new(|| -> () {
*value.borrow_mut() = 1;
}));
(a.closure().unwrap())();
println!("New value = {}", value.borrow());
}
但我收到此错误:
Compiling playground v0.0.1 (/playground)
error[E0597]: `value` does not live long enough
--> src/main.rs:34:38
|
34 | a.set_closure(Box::new(|| -> () { *value.borrow_mut() = 1; }));
| ---------------------^^^^^---------------------
| | | |
| | | borrowed value does not live long enough
| | value captured here
| cast requires that `value` is borrowed for `'static`
...
38 | }
| - `value` dropped here while still borrowed
请问有人知道我需要做什么吗? 感谢您提前回复。
【问题讨论】:
标签: rust closures smart-pointers