我想在两个闭包之间共享一个引用;在一个封闭中可变。这是一个人为的情况,但我发现在学习 Rust 的背景下它很有趣。
为了使其工作,我不得不利用Rc,Weak和RefCell。有没有更简单的方法来实现这一目标?
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Foo {
i: i32,
}
impl Foo {
fn get(&self) -> i32 {
self.i
}
fn incr(&mut self) {
self.i += 1
}
}
fn retry<O, N>(mut operation: O, mut notify: N) -> i32
where
O: FnMut() -> i32,
N: FnMut() -> (),
{
operation();
notify();
operation()
}
fn something(f: &mut Foo) {
let f_rc = Rc::new(RefCell::new(f));
let f_weak = Rc::downgrade(&f_rc);
let operation = || {
// f.get()
let cell = f_weak.upgrade().unwrap();
let f = cell.borrow();
f.get()
};
let notify = || {
// f.incr();
let cell = f_weak.upgrade().unwrap();
let mut f = cell.borrow_mut();
f.incr();
};
retry(operation, notify);
println!("{:?}", f_rc);
}
fn main() {
let mut f = Foo { i: 1 };
something(&mut f);
}
Run Code Online (Sandbox Code Playgroud)
这里不需要引用计数,因为实体比任何闭包的寿命都长。你可以逃脱:
fn something(f: &mut Foo) {
let f = RefCell::new(f);
let operation = || f.borrow().get();
let notify = || {
f.borrow_mut().incr();
};
retry(operation, notify);
println!("{:?}", f);
}
Run Code Online (Sandbox Code Playgroud)
这很简单。
采用RefCell然而,有必要将强制执行移动别名XOR可变性,从编译时到运行时。
| 归档时间: |
|
| 查看次数: |
509 次 |
| 最近记录: |