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
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.