Iter sum to a larger datatype

I am trying to work on an iterative sum, where the sum could be greater than the individual datatype limit. This is running into an overflow situation (which it should). Any idea on how to navigate the problem?

let vec : Vec<u8> = vec![100, 2, 3, 100, 100];
let sum : u32 = vec.iter().sum();
2 Likes

Here's one way to do it. I'm not positive, but I don't there there is hardly any performance hit with the cast using as in the map().

let vec : Vec<u8> = vec![100, 2, 3, 100, 100];
let sum : u32 = vec.iter().map(|&x| x as u32).sum();
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.