Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

parsing - Cannot infer type for `B` for filter_map().sum()

The code below reads numbers, sums them, then prints the sum. I've tried few annotations, but it didn't work. I must be missing something. How could I make it work?

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);
}

Error message from compiler:

type annotations needed
 --> srcmain.rs:9:10
  |
9 |         .filter_map(|w| w.parse().ok())
  |          ^^^^^^^^^^ cannot infer type for `B`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's look up the signature of filter_map to see, what the complain is about:

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B>, 

Okay, so Option<B> is the result, which means he cannot infer what w.parse().ok() will be.

Let's try to give him a hint

.filter_map(|w| w.parse::<i32>().ok())

Let's compile an see.... Hurray!

So, lesson learned: Look up the signature and try to figure out, which part the compiler cannot infer and try to specify it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...