Iterator::fold() / any() / all() / find()
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
| Method | Description |
|---|---|
| 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
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)
}
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 contact us.