我想寫一個函數,它需要一個類型爲Fn() ->()
的閉包集合,即每個閉包都不帶參數,不返回任何東西(我希望它們實際上是FnOnce
,以便將其所有環境移動到閉包對象中) 。如何編寫一個需要收集閉包的函數?
我已經嘗試了很多東西(如使用Box<Fn() ->()>
和使用&'static
),但我無法得到這個工作。
我在Rust Playground中創建了一個要點,以展示我正在嘗試做的事情。
這裏的簡化代碼:
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)),
));
}
錯誤:
error[E0271]: type mismatch resolving `<[[email protected]/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<[[email protected]/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}>, [[email protected]/main.rs:11:9: 11:49]>`
= note: required by `run_all_tests`