且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-22 22:09:08

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

Reference counting is unnecessary here because the entity lives longer than any of the closures. You can get away with:

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);
}

这很简单.

然而,RefCell 的使用对于将别名异或可变性的实施从编译时移到运行时是必要的.

The use of RefCell, however, is necessary to move the enforcement of the Aliasing XOR Mutability from compile-time to run-time.