I want to write concise code. Here is a snippet that fails for mysterious reasons:
let va: &mut Vec<f64> = &mut Vec::new();
va.push(5.0);
let avg: f64 = va.iter().sum() / 2.0;
The error message is:
error[E0283]: type annotations required: cannot resolve `_: std::iter::Sum<&f64>`
--> src/main.rs:36:30
|
36 | let avg: f64 = va.iter().sum() / 2.0;
| ^^^
Putting types everywhere doesn't help either.
let avg: f64 = va.iter().sum() as f64 / 2.0f64;
Error:
error[E0282]: type annotations needed
--> src/main.rs:36:20
|
36 | let avg: f64 = va.iter().sum() as f64 / 2.0f64;
| ^^^^^^^^^^^^^^^^^^^^^^ cannot infer type for `S`
|
= note: type must be known at this point
The following code, which is a trivial rewrite, works:
let va: &mut Vec<f64> = &mut Vec::new();
va.push(5.0);
let sum: f64 = va.iter().sum();
let avg: f64 = sum / 2.0;
This problem is the same for any other arithmetic operation. What is the logic behind this behavior of the compiler?
My question is not about the Turbofish syntax.