How can callbacks with captured mutable variables

2019-01-08 00:01发布

Foo can be modified using the method .modify():

struct Foo;
impl Foo {
    fn modify(&mut self) {}
}

Bar stores a callback:

struct Bar<'a> {
    callback: Box<FnMut() + 'a>,
}
impl<'a> Bar<'a> {
    fn new<F: FnMut() + 'a>(f: F) -> Bar<'a> {
        Bar {
            callback: Box::new(f),
        }
    }
}

init() takes a slice of Bar and executes their callbacks:

fn init(bars: &mut [Bar]) {
    for b in bars {
        (*b.callback)();
    }
}

And now the most interesting:

Changing Foo in a loop works fine; on each iteration of the loop foo is mutably borrowed and .modify() is called:

fn main() {
    let mut foo = Foo;

    for _ in 0..10 {
        foo.modify();
    }
}

Changing Foo inside of the callbacks does not work:

fn main() {
    let mut foo = Foo;

    let mut bar1 = Bar::new(|| foo.modify());
    let mut bar2 = Bar::new(|| foo.modify());

    init(&mut [bar1, bar2]);
}

Try it on the playground, it has an error:

error[E0499]: cannot borrow `foo` as mutable more than once at a time
  --> src/main.rs:27:29
   |
26 |     let mut bar1 = Bar::new(|| foo.modify());
   |                             -- --- previous borrow occurs due to use of `foo` in closure
   |                             |
   |                             first mutable borrow occurs here
27 |     let mut bar2 = Bar::new(|| foo.modify());
   |                             ^^ --- borrow occurs due to use of `foo` in closure
   |                             |
   |                             second mutable borrow occurs here
...
30 | }
   | - first borrow ends here

How to implement a similar guarantee for item 2?

标签: callback rust
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-08 01:01

You can use RefCell:

let foo = RefCell::new(Foo);

{
    let bar1 = Bar::new(|| foo.borrow_mut().modify());
    let bar2 = Bar::new(|| foo.borrow_mut().modify());
    init(&mut [bar1, bar2]);
}

let mut foo = foo.into_inner(); // extract foo to use in external API

Be careful with borrow_mut(), it panics if the value is currently borrowed.


If you can change Bar and init(), you can pass value foo to the init() separate from the method modify():

struct Bar<'a> {
    callback: Box<FnMut(&mut Foo) + 'a>,
}
impl<'a> Bar<'a> {
    fn new<F: FnMut(&mut Foo) + 'a>(f: F) -> Bar<'a> {
        Bar {
            callback: Box::new(f),
        }
    }
}

fn init(bars: &mut [Bar], arg: &mut Foo) {
    for b in bars {
        (*b.callback)(arg);
    }
}
let mut bar1 = Bar::new(|x| x.modify());
let mut bar2 = Bar::new(Foo::modify); // you can pass it without closure
init(&mut [bar1, bar2], &mut foo);
查看更多
登录 后发表回答