Rust Guide > Documentation > Iterators > Fold

Introduction

The fold function in Rust is a method provided by the Iterator trait that allows you to accumulate or reduce the elements of an iterator into a single value. This function is useful for a wide range of tasks, such as summing numbers, concatenating strings, or building complex data structures.

Syntax

The basic syntax of the fold function is as follows:

iterator.fold(initial_value, |accumulator, item| {
    // combine accumulator and item
})

Here, iterator is any type that implements the Iterator trait, initial_value is the starting value for the accumulation, and |accumulator, item| is a closure that defines how to combine the accumulator and each item.

Example Usage

Example 1: Summing Numbers

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let sum = numbers.iter().fold(0, |acc, &x| acc + x);
    println!("Sum: {}", sum); // Output: Sum: 15
}

Example 2: Concatenating Strings

fn main() {
    let words = vec!["hello", " ", "world"];
    let sentence = words.iter().fold(String::new(), |mut acc, &x| {
        acc.push_str(x);
        acc
    });
    println!("{}", sentence); // Output: hello world
}

Example 3: Finding the Maximum Value

fn main() {
    let numbers = vec![3, 5, 1, 9, 2];
    let max = numbers.iter().fold(i32::MIN, |acc, &x| acc.max(x));
    println!("Max: {}", max); // Output: Max: 9
}

Example 4: Counting Occurrences

use std::collections::HashMap;

fn main() {
    let chars = vec!['a', 'b', 'a', 'c', 'b', 'a'];
    let mut counts = HashMap::new();
    chars.iter().fold(&mut counts, |acc, &x| {
        *acc.entry(x).or_insert(0) += 1;
        acc
    });
    println!("{:?}", counts); // Output: {'a': 3, 'b': 2, 'c': 1}
}

Example 5: Building a Custom Data Structure

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let points = vec![(1, 2), (3, 4), (5, 6)];
    let sum_point = points.iter().fold(Point { x: 0, y: 0 }, |acc, &(x, y)| Point {
        x: acc.x + x,
        y: acc.y + y,
    });
    println!("{:?}", sum_point); // Output: Point { x: 9, y: 12 }
}

Considerations

  • The fold method is useful for reducing an iterator to a single value, but it can be less efficient than specialized methods like sum or product for specific tasks. This is because those specialized methods may be directly implemented and optimized in the standard library.

See Also

  • collect - Transforms an iterator into a collection such as a vector or hash map.
  • map - Transforms each element of an iterator and returns a new iterator with the transformed elements.
  • for_each - Applies a closure to each element of an iterator for side effects.