Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Experience report: Aligning type-erased closure bounds #3

Closed
crlf0710 opened this issue Aug 28, 2021 · 0 comments
Closed

Experience report: Aligning type-erased closure bounds #3

crlf0710 opened this issue Aug 28, 2021 · 0 comments

Comments

@crlf0710
Copy link
Member

crlf0710 commented Aug 28, 2021

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.

@crlf0710 crlf0710 changed the title Experience report: Aligning closure bounds Experience report: Aligning type-erased closure bounds Aug 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant