Skip to content
Tutorials Center
My learning

Topics

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.

Rust
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

Rust Totals

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.

Rust Overflow, Option and Result sums

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

Rust
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 turbofish sum::<T>() or a typed let fixes it.
  • Mixed types need a conversion first. You cannot sum u8 items into a u32 directly; map with u32::from first (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 NaN makes the whole sum NaN.
  • count() walks the iterator and is O(n) for most adapters, including filter. For a collection's length use .len(); for an ExactSizeIterator use its len() rather than count().
  • 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.
  • Sum and Product are traits you can implement for your own numeric-like types (impl Sum for Money), which makes .sum::<Money>() work. See Sum and Product.
  • Related checked helpers: use try_fold with checked_add, or fold with saturating_add/wrapping_add, to choose the overflow behavior yourself.