Poblem with Arc<Mutex<Box<FnMut + Send>>>


First, sorry for my English, it isn't my mother language!

I'm learning Rust (very interesting), and I had a problem with boxed closure.
My goal is to play with kind of "actor", that can run a closure from time to time, in a thread.

Here I have a working version of it, without thread : Rust Playground. The Run struct is the "actor", and own a closure. So for that, the closure is boxed (to be Sized and on the heap).
I want this closure run in it's own thread. Here is a try : Rust Playground. The idea is to put the closure in an Arc Mutex to be shareable and mutable between threads.
But I have this error:

<anon>:20:13: 20:17 error: cannot borrow immutable `Box` content as mutable
<anon>:20             (f2)();

Can someone explain me this error? Because I don't understand why the deref of the box is not mutable...

Thank you in advance,

Derefs are weird like this: they don't seem to select a mutable variant like one might expect. You can force it with an explicit &mut:

    let f2 = &mut *f.lock().unwrap();

Maybe this is just Rust's way of making us be explicit about mutability.


Thank you for this quick answer! It fix my problem. I was not aware about the deref notation (&mut *)

You've found a bug, I wonder if it has an issue reported already.

#27106 might be the issue

1 Like