Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

rust - How can callbacks with captured mutable variables be treated like normal mutable borrows?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...