Closed
Description
Code description
It's common to switch between single-threaded and multithread processing according to runtime options. However their underlying APIs usually exhibits different bounds. For example:
fn process_in_single_thread(callback: &mut dyn FnMut()) {
callback();
}
fn process_in_thread_pool(callback: &(dyn Fn() + Sync)) {
callback();
}
By using trait upcasting coercion, a single type-erased closure reference can be passed to both these methods.
pub fn foo(f: &mut (dyn Fn() + Sync)) {
let multithread = true;
if !multithread {
process_in_single_thread(f);
} else {
process_in_thread_pool(f);
}
}
What worked well
It's really nice that &mut dyn Fn
can now be used as if it's a &mut dyn FnMut
.
What worked less well
Nothing in this example.