Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Iterator::fold() / any() / all() / find()

Iterator::fold() / any() / all() / find()

Since: Rust 1.0(2015)

Rust iterators provide terminal operations for accumulation with fold(), conditional checks with any() and all(), and element searching with find() and position().

Syntax

// fold(): Accumulates values using an initial value and a closure.
let sum = vec![1, 2, 3, 4, 5].iter().fold(0, |acc, x| acc + x); // 15

// any(): Returns true if at least one element satisfies the condition.
let has_even = vec![1, 3, 5, 6].iter().any(|x| x % 2 == 0); // true

// all(): Returns true if every element satisfies the condition.
let all_pos = vec![1, 2, 3].iter().all(|x| *x > 0); // true

// find(): Returns the first element satisfying the condition as Option<&T>.
let first_even = vec![1, 3, 4, 6].iter().find(|&&x| x % 2 == 0); // Some(4)

// position(): Returns the index of the first element satisfying the condition as Option<usize>.
let idx = vec![1, 3, 4, 6].iter().position(|&x| x % 2 == 0); // Some(2)

Method List

MethodDescription
iter.fold(init, |acc, x| ...)Returns the accumulated result starting from an initial value, applied through a closure.
iter.reduce(|acc, x| ...)Similar to fold(), but without an initial value (the first element is used as the initial value). Returns an Option.
iter.any(|x| ...)Returns true if at least one element satisfies the condition.
iter.all(|x| ...)Returns true if all elements satisfy the condition (returns true for an empty iterator).
iter.find(|x| ...)Returns the first element satisfying the condition as Option<&T>.
iter.find_map(|x| ...)Returns the first Some result from the closure as Option<T>.
iter.position(|x| ...)Returns the index of the first element satisfying the condition as Option<usize>.
iter.rposition(|x| ...)Searches from the end and returns the index as Option<usize>.
iter.scan(state, |s, x| ...)Returns an iterator that transforms elements while maintaining internal state.

Sample Code

sample_iter_fold_any_all_find.rs
fn main() {
    let numbers = vec![1, 2, 3, 4, 5];

    // fold(): Calculate the sum.
    let sum = numbers.iter().fold(0, |acc, &x| acc + x);
    println!("fold (sum): {}", sum); // 15

    // fold(): Find the maximum value.
    let max = numbers.iter().fold(i32::MIN, |acc, &x| acc.max(x));
    println!("fold (max): {}", max); // 5

    // fold(): Concatenate strings.
    let words = vec!["Hello", " ", "World"];
    let sentence = words.iter().fold(String::new(), |mut acc, s| {
        acc.push_str(s);
        acc
    });
    println!("fold (string concat): {}", sentence);

    // reduce(): Accumulate without an initial value.
    let product = numbers.iter().copied().reduce(|acc, x| acc * x);
    println!("reduce (product): {:?}", product); // Some(120)

    // any(): Check if any element satisfies the condition.
    let has_negative = numbers.iter().any(|&x| x < 0);
    let has_five = numbers.iter().any(|&x| x == 5);
    println!("Has negative?: {}", has_negative); // false
    println!("Has five?: {}", has_five); // true

    // all(): Check if all elements satisfy the condition.
    let all_positive = numbers.iter().all(|&x| x > 0);
    let all_even = numbers.iter().all(|&x| x % 2 == 0);
    println!("All positive?: {}", all_positive); // true
    println!("All even?: {}", all_even); // false

    // find(): Find the first element satisfying the condition.
    let first_even = numbers.iter().find(|&&x| x % 2 == 0);
    println!("First even: {:?}", first_even); // Some(2)

    let not_found = numbers.iter().find(|&&x| x > 100);
    println!("Greater than 100: {:?}", not_found); // None

    // position(): Get the index of an element.
    let pos = numbers.iter().position(|&x| x == 3);
    println!("Index of 3: {:?}", pos); // Some(2)

    // find_map(): Extract the first Some while transforming elements.
    let strs = vec!["abc", "42", "xyz"];
    let first_num = strs.iter().find_map(|s| s.parse::<i32>().ok());
    println!("First number: {:?}", first_num); // Some(42)
}

Compile with the following command:

rustc iter_fold_any_all_find.rs
./iter_fold_any_all_find
fold (sum): 15
fold (max): 5
fold (string concat): Hello World
reduce (product): Some(120)
Has negative?: false
Has five?: true
All positive?: true
All even?: false
First even: Some(2)
Greater than 100: None
Index of 3: Some(2)
First number: Some(42)

Common Mistakes

Common mistake 1: wrong type for the initial value of fold()

The initial value of fold() determines the return type. Make sure it matches the intended output type.

fn main() {
    let data = vec![1, 2, 3, 4, 5];

    // Initial value 0i32 — sum of integers
    let sum = data.iter().fold(0i32, |acc, &x| acc + x);
    println!("sum: {}", sum); // 15

    // For string concatenation, the initial value is an empty String
    let words = vec!["Goku", "Vegeta", "Gohan"];
    let joined = words.iter().fold(String::new(), |mut acc, &s| {
        if !acc.is_empty() { acc.push_str(", "); }
        acc.push_str(s);
        acc
    });
    println!("{}", joined); // Goku, Vegeta, Gohan
}

Common mistake 2: find() returns a reference, not the value itself

find() returns Option<&T>. Dereference the result or call copied() to obtain the value directly.

fn main() {
    let numbers = vec![1, 3, 5, 4, 7];

    // find() returns Option<&i32> (a reference)
    let found = numbers.iter().find(|&&x| x % 2 == 0);
    println!("{:?}", found); // Some(4)

    // Destructure the reference to get the value
    if let Some(&val) = found {
        println!("even value: {}", val); // 4
    }

    // Or use copied() to convert Option<&i32> to Option<i32>
    let found_val = numbers.iter().find(|&&x| x % 2 == 0).copied();
    println!("{:?}", found_val); // Some(4)
}

Notes

Both any() and all() use short-circuit evaluation. any() stops as soon as it finds the first element returning true, and all() stops as soon as it finds the first element returning false.

fold() is a general-purpose operation that can express any kind of aggregation. However, when a dedicated method exists — such as sum() for totals or max() for maximum values — prefer those for clearer intent.

For the basics of collecting and aggregating, see Iterator::collect() / count() / sum().

If you find any errors or copyright issues, please .