Rust Reference ยท Iterators
Iterator sum, product and count
Reference for Iterator::sum, product and count in Rust: type annotations, empty iterators, floats, overflow panics, and summing Option and Result items.
sum() adds up all items, product() multiplies them, and count() tells you how many there were. They are consuming methods: they run the whole iterator and return a single value. count() always returns a usize; sum() and product() return whatever numeric type you ask for.
That last point is the one thing to remember. The result type of sum is a generic parameter, so there is no default, and you must name it: let total: i32 = v.iter().sum(); or v.iter().sum::<i32>(). The same methods work for floats, for Wrapping, Duration and for Option or Result wrappers of those.
let total: i32 = [1, 2, 3].iter().sum(); // 6 let fact: u64 = (1..=5).product(); // 120 let evens = (1..=10).filter(|n| n % 2 == 0).count(); // 5
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn sum<S>(self) -> S where S: Sum<Self::Item>; fn product<P>(self) -> P where P: Product<Self::Item>; fn count(self) -> usize;
| Name | Description |
|---|---|
S / P |
The result type. Integers and floats can sum both T and &T items, so iter().sum() works without copied(). |
Returns: the total, the product, or the number of items.
Edge cases and panics: an empty iterator gives 0 (additive identity), 1 (multiplicative identity) or 0 for count. In a build with overflow checks (debug, and every TryIt on this site) integer overflow panics with "attempt to add with overflow"; in a release build it silently wraps.
Usage notes
- Always annotate the result.
let s = v.iter().sum();fails with "type annotations needed". The turbofishsum::<T>()or a typedletfixes it. - Mixed types need a conversion first. You cannot sum
u8items into au32directly; map withu32::fromfirst (as above) or use.map(|&b| b as u32). - Floating-point order matters. Adding the same numbers in a different order can give slightly different results, and a single
NaNmakes the whole sumNaN. count()walks the iterator and is O(n) for most adapters, includingfilter. For a collection's length use.len(); for anExactSizeIteratoruse itslen()rather thancount().- Counting matches:
iter().filter(pred).count()is the idiom;iter().any(pred)is cheaper when you only need to know whether there is at least one. - Averages need both the sum and the length. For a one-pass average of an iterator without a known length, fold a
(sum, count)pair. SumandProductare traits you can implement for your own numeric-like types (impl Sum for Money), which makes.sum::<Money>()work. SeeSumandProduct.- Related checked helpers: use
try_foldwithchecked_add, orfoldwithsaturating_add/wrapping_add, to choose the overflow behavior yourself.