问题
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.
回答1:
This is specifically mentioned in the documentation for parse() (emphasis mine):
Because
parseis 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.
parsecan 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.
来源:https://stackoverflow.com/questions/56123213/why-cant-the-rust-compiler-infer-the-type-when-calling-parse