我编写了下面的Rust程序来打印出只有整数的命令行参数。它完美的作品:Rust函数的返回类型中的关闭
use std::env;
fn main() {
for i in env::args().filter_map(|arg| arg.parse::<i32>().ok()) {
println!("{}", i);
}
}
然后,我试图重新编写程序将过滤器抽象为函数。这个版本不能编译。
use std::env::Args;
use std::env;
use std::iter::FilterMap;
// Version 2
fn main() {
for i in nums(&env::args()) {
println!("{}", i);
}
}
fn nums<F: Fn(String) -> Option<i32>>(args: &Args) -> FilterMap<Args,F> {
args.filter_map(|arg| arg.parse::<i32>().ok())
}
它产生以下编译错误:
Compiling iterator_return_type v0.1.0 (file:///Users/gabriel/AllProjects/SentimentAnalysis/iterator_return_type)
error[E0282]: type annotations needed
--> src/main.rs:16:9
|
16 | for i in nums(&env::args()) {
| ^cannot infer type for `_`
error: the type of this value must be known in this context
--> src/main.rs:22:27
|
22 | args.filter_map(|arg| arg.parse::<i32>().ok())
| ^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/main.rs:22:21
|
22 | args.filter_map(|arg| arg.parse::<i32>().ok())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter, found closure
|
= note: expected type `F`
found type `[[email protected]/main.rs:22:21: 22:50]`
error: aborting due to previous error(s)
error: Could not compile `iterator_return_type`.
我觉得特别困惑什么是最终的编译错误。我不明白我还可以指定一个闭包类型。
谢谢!
该问题给出的解决方案不适用于我的示例。在那个问题中,Split迭代器是返回类型。 FilterMap迭代器需要一个闭包类型参数。这是一个完全不同的问题。 –
您应该认真考虑重命名问题的标题,因为它强烈建议重复上述建议。你似乎有更多的“不能引用封闭类型”的问题。 –
好的建议,谢谢!我已经这样做了。 –