Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't the sum of a `Vec<i64>` known to be `Option<i64>`?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading