gpt4 book ai didi

rust - Rust 函数的返回类型中的闭包

转载 作者:行者123 更新时间:2023-11-29 08:06:15 24 4
gpt4 key购买 nike

<分区>

我编写了以下 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 `[closure@src/main.rs:22:21: 22:50]`

error: aborting due to previous error(s)

error: Could not compile `iterator_return_type`.

令我特别困惑的是最后的编译错误。我不明白我还可以如何指定闭包类型。

谢谢!

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com