I am trying to write a function that takes a collection of closures of type Fn() -> ()
, i.e. each closure takes no args, returns nothing (and I want them to be FnOnce
actually, so as to move all its environment into the closure object).
I've tried many things (like using Box<Fn() -> ()>
and using &'static
) but I just can't get this working.
I created a gist in the Rust Playground to show what I am trying to do, approximately.
Here's the simplified code:
fn run_all_tests<I>(tests: I)
where
I: IntoIterator<Item = Box<FnOnce() -> ()>>,
{
}
fn main() {
let examples = [1, 2, 3];
run_all_tests(examples.iter().map(
|ex| Box::new(move |ex| assert!(ex > 0)),
));
}
The error:
error[E0271]: type mismatch resolving `<[closure@src/main.rs:11:9: 11:49] as std::ops::FnOnce<(&{integer},)>>::Output == std::boxed::Box<std::ops::FnOnce() + 'static>`
--> src/main.rs:10:5
|
10 | run_all_tests(examples.iter().map(
| ^^^^^^^^^^^^^ expected closure, found trait std::ops::FnOnce
|
= note: expected type `std::boxed::Box<[closure@src/main.rs:11:23: 11:48]>`
found type `std::boxed::Box<std::ops::FnOnce() + 'static>`
= note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<std::slice::Iter<'_, {integer}>, [closure@src/main.rs:11:9: 11:49]>`
= note: required by `run_all_tests`