270 words
1 minutes
260202_fold_sum_product_compare

link#


Here’s a comparison of the three iterator reduction methods in Rust:#

FunctionPurposeWhen to UseReturn TypeExample
fold(init, f)Reduce an iterator using a custom accumulator function.When you need custom logic, multiple values, or a different output type.Any type B (chosen by you)iter.fold(0, |acc, x| acc + x)
sum()Add all elements together.When you simply want the total of numeric values.A type implementing std::iter::Sum (usually the element type)iter.sum::<i32>()
product()Multiply all elements together.When you want the product of numeric values.A type implementing std::iter::Product (usually the element type)iter.product::<i32>()

Return type examples#

Input Iteratorfold()sum()product()
Iterator<Item = i32>i32, f64, String, (i32, usize), Vec<_>, HashMap<_, _>, etc.i32, i64, f64, etc.i32, i64, f64, etc.
Iterator<Item = &str>String (concatenation), usize (count bytes), etc.❌ Not supported❌ Not supported

Which one should I choose?#

If you want to…Use
Add all valuessum()
Multiply all valuesproduct()
Count while summingfold()
Compute an average (sum and count together)fold()
Build a Stringfold()
Build a Vec, HashMap, or custom structfold()
Return a completely different type than the iterator itemsfold()

Rule of thumb#

  • Use sum() when your intent is “add everything.”
  • Use product() when your intent is “multiply everything.”
  • Use fold() when the computation is anything more general than summing or multiplying, or when the accumulator/result type differs from the iterator’s item type. fold() is the most flexible because it can return any type you define through its initial accumulator and closure.

fold() Examples#

  • fold() → Any return type
let nums = [1, 2, 3, 4];

let result: (i32, usize) = nums.iter().fold((0, 0), |(sum, count), &x| {
    (sum + x, count + 1)
});
  • Returns:
(i32, usize)

sum()#

let nums = [1, 2, 3, 4];

let sum: i32 = nums.iter().sum();
  • Returns:
i32

product()#

let nums = [1, 2, 3, 4];

let product: i32 = nums.iter().product();
  • Returns:
i32
260202_fold_sum_product_compare
https://younghakim7.github.io/blog/posts/260202_fold_sum_product_compare/
Author
YoungHa
Published at
2026-02-02