Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The Sum and Product traits

Reference for Rust Sum and Product: how Iterator::sum and product work, built-in impls for numbers, Option and Result, references, and implementing them for custom types.

Sum and Product are the traits behind Iterator::sum() and Iterator::product(). They describe how to combine many items of one type into a single value, starting from the additive identity (zero) or the multiplicative identity (one). The standard library implements them for all integer and float types, for Wrapping and Saturating numbers, for Duration, and for Option and Result wrappers of those.

Implement Sum for your own type to make iter.sum::<MyType>() work. As with collect, the result type usually has to be named, because many types could be the answer.

Rust
let total: i32 = [1, 2, 3].iter().sum();

Try it

Rust sum and product over built-in types

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 Sum and Product for a custom type

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
pub trait Sum<A = Self>: Sized {
    fn sum<I: Iterator<Item = A>>(iter: I) -> Self;
}

pub trait Product<A = Self>: Sized {
    fn product<I: Iterator<Item = A>>(iter: I) -> Self;
}

fn Iterator::sum<S: Sum<Self::Item>>(self) -> S;
fn Iterator::product<P: Product<Self::Item>>(self) -> P;
Name Description
A The item type being combined; defaults to Self. References (&'a T) are separate impls.
iter The iterator to consume.

Returns: the combined value, or the identity (0, 0.0, 1, ...) for an empty iterator.

Errors / panics / edge cases: integer sum and product panic on overflow in debug builds and wrap in release builds. Use fold with checked_add, or sum into a wider type, when overflow is possible. Float sums are not associative, so order affects the last digits.

Usage notes

  • The result type must be known. let n = v.iter().sum(); fails with "type annotations needed"; write sum::<i32>() or annotate the binding.
  • References are supported for built-in numbers. iter().sum::<i32>() works on &i32 items thanks to the Sum<&i32> impl; for your own type, add the Sum<&'a T> impl as above.
  • Early exit with Option/Result. The wrappers short-circuit on the first None or Err, which parses and validates in one pass.
  • Empty means identity. The empty sum is zero and the empty product is one, which is mathematically consistent but occasionally surprising. Check is_empty when zero is not meaningful.
  • Equivalent to fold. sum() is just a fold with + starting at zero, and the compiler optimizes both well.
  • Need only an operator? If your type implements Add and Default, you can write a short fold yourself without implementing Sum.
  • Max and min are separate: Iterator::max, min, max_by_key and reduce cover other reductions.