2

I'm writing a sum calculator in Rust, but I found that the Rust compiler can't infer a type in some cases. Here is the code.

fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let sum = s.split_whitespace()
        .filter_map(|c| c.parse().ok())
        .fold(0, |a, b| a + b);
    println!("{}", sum);
}

The Rust compiler told me:

error[E0282]: type annotations needed
 --> src/main.rs:6:22
  |
6 |         .fold(0, |a, b| a + b);
  |                      ^ consider giving this closure parameter a type

However, IntelliJ IDEA infers the type is i32.

If we type let a = 0;, the type of a is i32 by default. I guess IDEA infer the type of initial value 0 of the fold function is i32, so the sum type in the fourth line can be inferred to i32 and c should be parsed to i32 on the next line. But why can't the Rust compiler infer the type?

I have also tried to declare the sum type in the fourth line, and the Rust compiler give me the same error. Why can't the Rust compiler infer the type in this case?

If I declare the parse() type or do as compiler told me, then it compiles.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
hzqelf
  • 857
  • 7
  • 17
  • 2
    IIRC IDEAs code does not rely on the rust compiler at all. Therefore if you encounter an error, always use rustc as a reference, never your IDE warnings/errors. – hellow May 14 '19 at 07:03

1 Answers1

4

This is specifically mentioned in the documentation for parse() (emphasis mine):

Because parse is so general, it can cause problems with type inference. As such, parse is one of the few times you'll see the syntax affectionately known as the 'turbofish': ::<>. This helps the inference algorithm understand specifically which type you're trying to parse into.

parse can parse any type that implements the FromStr trait.

There are many implementors of FromStr, which is why you have to tell Rust exactly which type you want to parse from the String.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
sdht0
  • 500
  • 4
  • 8
  • 4
    Note also that `i32` implements both [`Add`](https://doc.rust-lang.org/stable/std/primitive.i32.html#impl-Add%3Ci32%3E) and [`Add<&i32>`](https://doc.rust-lang.org/stable/std/primitive.i32.html#impl-Add%3C%26%27a%20i32%3E), so knowing that `a` is `i32` still leaves two possibilities for the type of `b`: it could be either `i32` or `&i32`. That's why you need to tell the compiler which one to take. – Jmb May 14 '19 at 06:28