Fold and collect
Quick answer
fold combines a sequence into one accumulator. collect builds a result collection from iterator items; its destination type determines what is constructed.
Accumulator and target type
fold(initial, |acc, item| ...) returns the final accumulator, or the initial value for empty input. Collect requires a suitable FromIterator implementation and often needs a type annotation. A fold processes items in iterator order, which matters for non-associative operations.
fn main() { let (count, total) = [3, 5, 7].into_iter().fold((0, 0), |(c, t), n| (c + 1, t + n)); println!("{count}: {total}");}Expected stdout (not executed):
3: 15The accumulator is a tuple with two independent fields.
use std::collections::BTreeSet;fn main() { let unique: BTreeSet<_> = [4, 2, 4].into_iter().collect(); println!("{unique:?}");}Expected stdout (not executed):
{2, 4}Collect uses the target set's uniqueness and ordering rules.
Common mistake
Do not expect collect to infer a unique destination when several collection types fit.
Try it yourself
Use fold to calculate the product of [2, 3, 4] and explain the empty-input result for initial value 1.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fold and collect — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
You collect an iterator of integers and want sorted distinct values. Which destination fits?
Fold and collect — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let (count, total) = [3, 5, 7].into_iter().fold((0, 0), |(c, t), n| (c + 1, t + n)); println!("{count}: {total}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Fold and collect — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::collections::BTreeSet; fn main() { let unique: BTreeSet<_> = [4, 2, 4].into_iter().collect(); println!("{unique:?}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.