【发布时间】:2017-07-30 10:20:25
【问题描述】:
我正在尝试编写一个函数,该函数采用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 `<[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`
【问题讨论】:
标签: rust