下面的代码读取数字,对它们求和,然后打印总和。我尝试了一些注释,但没有用。我肯定错过了什么。我怎样才能让它发挥作用?
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);
}
来自编译器的错误信息:
type annotations needed
--> src\main.rs:9:10
|
9 | .filter_map(|w| w.parse().ok())
| ^^^^^^^^^^ cannot infer type for `B`
最佳答案
让我们查看 filter_map 的签名,看看提示的是什么:
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B>,
好的,所以 Option<B>
是结果,这意味着他无法推断出什么w.parse().ok()
会的。
我们试着给他一个提示
.filter_map(|w| w.parse::<i32>().ok())
让我们编译一下……万岁!
所以,吸取教训:查找签名并尝试找出编译器无法推断的部分并尝试指定它。
关于parsing - 无法为 filter_map().sum() 推断 `B` 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283403/