如果值超过闭包,在闭包之间共享引用的正确方法是什么?

Arn*_*anc 2 rust

我想在两个闭包之间共享一个引用;在一个封闭中可变。这是一个人为的情况,但我发现在学习 Rust 的背景下它很有趣。

为了使其工作,我不得不利用RcWeakRefCell。有没有更简单的方法来实现这一目标?

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)

Mat*_* M. 5

这里不需要引用计数,因为实体比任何闭包的寿命都长。你可以逃脱:

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可变性,从编译时到运行时。