The problem with Fn()
is that you can call it multiple times. If you moved out of a captured value, that value would not be available anymore at the next call. You need a FnOnce()
to make sure calling the closure also moves out of it, so it’s gone and can’t be called again.
There’s no way to have an Arc<Mutex<(FnOnce() + Send + Sync + 'static)>>
. This would again require that you statically guarantee that after you call the function, noone else can call it again. Which you cannot, since someone else might have another Arc
pointing to your FnOnce
. What you can do is box it and send it as Box<FnOnce() + Send + Sync + 'static>
. There’s only ever one owner of a Box
.
The trouble with FnOnce()
is, is that you can’t really call it while it’s in the Box
, because that would require moving it out of the Box
and calling it. But we don’t know the size of it, so we cannot move it out of the Box
. In the future Box<FnOnce()>
closures might become directly usable.
“Luckily” this problem occurred more often, so there’s FnBox
. Sadly this requires nightly to work. Also I couldn’t figure out how to use the function call syntax that is described in the docs, but you can manually call call_box
on the Box<FnBox()>
. Try it out in the Playground