parsing - 无法为 filter_map().sum() 推断 `B` 的类型

标签 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_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/

相关文章:

Rust:在 LLVM Bitcode 中包含依赖项

macros - 如何有条件地更改 Rust 宏的一小部分?

java - 看不懂CYK算法伪代码

list - 展平列表列表

javascript - 动态地从json中选择元素

types - 函数式语言是否使用来自调用者的信息进行类型推断?

Golang : How to convert an image. 图像到 uint16

rust - 为什么联合上的模式匹配会出现无法访问的模式警告?

json - 关于 EBNF 表示法和 JSON 的问题

java - 子级的 JSoup 格式输出