Parsing 无法为筛选器映射()推断'B'的类型。sum()
下面的代码读取数字,求和,然后打印和。我尝试了一些注释,但没有效果。我一定错过了什么。我怎样才能让它工作Parsing 无法为筛选器映射()推断'B'的类型。sum(),parsing,types,rust,type-inference,Parsing,Types,Rust,Type Inference,下面的代码读取数字,求和,然后打印和。我尝试了一些注释,但没有效果。我一定错过了什么。我怎样才能让它工作 use std::io; use std::io::Read; fn main() { let mut buff = String::new(); io::stdin().read_to_string(&mut buff).expect("read_to_string error"); let v: i32 = buff .split_wh
use std::io;
use std::io::Read;
fn main() {
let mut buff = String::new();
io::stdin().read_to_string(&mut buff).expect("read_to_string error");
let v: i32 = buff
.split_whitespace()
.filter_map(|w| w.parse().ok())
.sum();
println!("{:?}", v);
}
来自编译器的错误消息:
需要类型注释
-->src\main.rs:9:10
|
9.filter_映射(| w | w.parse().ok())
|^^^^^^^^^^无法推断'B'的类型`
快速解决方法是说出您正在解析的类型:
let v: i32 = buff
.split_whitespace()
.filter_map(|w| w.parse::<i32>().ok())
.sum();
让我们查看filter_map的签名,查看投诉内容:
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B>,
让我们编译一个see。。。。万岁
因此,经验教训是:查找签名并尝试找出编译器无法推断的部分,然后尝试指定它。我们确实编写了
v:i32
,那么为什么编译器不能推断出这一点呢?因为这是对求和函数的提示。如果你只是写让v=…
你必须指定sum的类型。sum::()
。但是如果编译器知道的类型。sum
,为什么它不能推断的类型。parse
?rustc
只能在该级别上进行推断吗?因为它们可能不同于w.parse:()
和.sum:()
example@hellow当前位置我认为这不是原因<代码>w.parse::()和。总和:()
。我认为这与以下事实更相关:sum()
不返回求和类型(称之为Item
),而是返回实现sum
的任何值。编译器失败,因为任何类型都可以应用。我将编译器消息解释为“我必须注释filter\u map
”,我没有想到这是关于解析的。谢谢。我补充了一点解释。您也可以对filter\u-map
进行注释,但这样看起来会不太舒服。我以前尝试过类似.filter\u-map的东西,这让我很困惑heh@DulguunOtgon第二个参数是函数类型。因此,最好是推断它。非常确定.ok()
是冗余的,因为结果
实现了到迭代器
就像选项一样。哦,如果你切换到平面地图,那就不用担心了。(我还是喜欢平面地图
)。
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B>,
.filter_map(|w| w.parse::<i32>().ok())