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.