What is the right way to share a reference between

2019-03-01 02:03发布

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 order to make it work, I had to make use of Rc, Weak, and RefCell. Is there a simpler way of achieving this?

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

标签: rust
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-01 02:17

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.

查看更多
登录 后发表回答