What is the right way to share a reference between closures if the value outlives the closures?

后端 未结 1 366
失恋的感觉
失恋的感觉 2021-01-22 00:44

I want to share a reference between two closures; mutably in one closure. This is an artificial situation, but I find it interesting in the context of learning Rust.

In

相关标签:
1条回答
  • 2021-01-22 01:00

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

    which is quite simpler.

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

    0 讨论(0)
提交回复
热议问题