If I run
fn my_func(v: Vec<i64>) {
let sum = v.into_iter().sum();
}
fn main() {
}
then Rust wants me to provide a type annotations and write
v.into_iter().sum::<i64>()
I’m just trying to understand – why?
>Solution :
If you look at the definition of the sum method on Iterator
you see that it is generic over the output type with S: Sum<Self::Item>.
This means you are free to implement the Sum trait for you own types and sum a Vec<i64> into you custom type. So the compiler can not infer what the type should be.
By the way the output is a S not an Option<S>. The sum::<i64> of an empty vector is 0.
Rust could have decided to define sum in "your" way:
fn sum(self) -> Option<Self::Item>
where
Self::Item : Add<Output=Self::Item>
but they did not to make it more general.