Iterating in Parallel over a Vector of Functions?

Is it possible?

I have a custom struct, which I want to pass to each of the functions in a vector of boxed functions ( Vec<Box<Fn(Struct1) -> Struct2>> ).

I tried to use Rayon (https://docs.rs/crate/rayon/1.0.3), but every time I get different errors: either Parallelterator is not implemented as a trait, or there’s no Send or Sync implementations for the boxed functions in the vector.

If it is possible, how exactly can it be done?

The problem you’re having is that the type you are iterating over needs to be Send, that is, that it is safe to move to other threads. A function that doesn’t close over any values will be ‘send’, but because in your code it’s been de-typed into a trait object, this type information has been lost. The solution is to explicitly let rust know that it’s also Send like, meaning your vec type will be

Vec<Box<dyn Fn(Struct1) -> Struct2 + Send>>

you might also need a + 'static at the end to tell rust that there are no associated lifetimes, maybe try without first.

EDIT Here’s a playground example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2b8b68c3216e4bffc48afa872fb5f476

EDIT 2 the dyn is optional but I find it helpful to remind me I’m using trait objects.

4 Likes

It’s not going to be like that soon, and there’s already a lint for it. Please do use the dyn keyword to denote trait objects because this will be the standard for the future.

2 Likes

That worked beautifully. No statics were necessary in the end. Many thanks.