Iterator::collect() / count() / sum()
Rust iterators support several consuming adapters (terminal operations): collect() to gather elements into a collection, count() to count elements, sum() to compute the total, and product() to compute the product. Calling a terminal operation consumes the iterator.
Syntax
// collect(): Collects iterator elements into a collection. let v: Vec<i32> = (1..=5).collect(); let s: String = vec!['a', 'b', 'c'].into_iter().collect(); // count(): Counts the number of elements. let n = (1..=10).filter(|x| x % 2 == 0).count(); // 5 // sum(): Computes the sum of all elements (a type annotation may be required). let total: i32 = vec![1, 2, 3, 4, 5].iter().sum(); // 15 // product(): Computes the product of all elements. let prod: i32 = vec![1, 2, 3, 4, 5].iter().product(); // 120 // min() / max(): Returns the minimum/maximum value (returns an Option). let min = vec![3, 1, 4, 1, 5].iter().min(); // Some(1) let max = vec![3, 1, 4, 1, 5].iter().max(); // Some(5)
Terminal Operations
| Method | Description |
|---|---|
| iter.collect::<型>() | Converts the iterator into a collection such as Vec or HashMap. |
| iter.count() | Returns the number of elements as a usize. |
| iter.sum::<T>() | Returns the sum of all elements (requires the Sum trait). |
| iter.product::<T>() | Returns the product of all elements (requires the Product trait). |
| iter.min() | Returns the minimum value as Option<&T>. |
| iter.max() | Returns the maximum value as Option<&T>. |
| iter.min_by_key(|x| ...) | Returns the element with the smallest key as an Option. |
| iter.max_by_key(|x| ...) | Returns the element with the largest key as an Option. |
| iter.last() | Returns the last element as an Option. |
| iter.nth(n) | Returns the nth element as an Option (zero-indexed). |
| iter.for_each(|x| ...) | Applies a closure to each element (an alternative to a for loop when the return value is not needed). |
Sample Code
use std::collections::HashMap;
fn main() {
// collect(): Collect into a Vec.
let v: Vec<i32> = (1..=5).collect();
println!("collect Vec: {:?}", v);
// collect(): Collect into a HashMap.
let map: HashMap<i32, i32> = (1..=5).map(|x| (x, x * x)).collect();
println!("collect HashMap: {:?}", map);
// collect(): Collect into a String.
let s: String = vec!['R', 'u', 's', 't'].into_iter().collect();
println!("collect String: {}", s);
// count(): Count elements that satisfy a condition.
let even_count = (1..=20).filter(|x| x % 2 == 0).count();
println!("Even numbers from 1 to 20: {}", even_count);
// sum(): Compute the sum.
let total: i32 = (1..=100).sum();
println!("Sum from 1 to 100: {}", total);
let float_sum: f64 = vec![1.1, 2.2, 3.3].iter().sum();
println!("float sum: {:.1}", float_sum);
// product(): Compute factorial (5! = 120).
let factorial: u64 = (1..=5).product();
println!("5! = {}", factorial);
// min() / max()
let data = vec![5, 3, 8, 1, 9, 2, 7];
println!("min: {:?}", data.iter().min()); // Some(1)
println!("max: {:?}", data.iter().max()); // Some(9)
// min_by_key() / max_by_key(): Compare by a specific field or key.
let words = vec!["hello", "hi", "hey", "world"];
let shortest = words.iter().min_by_key(|w| w.len());
let longest = words.iter().max_by_key(|w| w.len());
println!("shortest: {:?}", shortest); // Some("hi")
println!("longest: {:?}", longest); // Some("hello") or "world"
// for_each(): Apply a closure to each element.
(1..=3).for_each(|x| println!("for_each: {}", x));
}
Output
collect Vec: [1, 2, 3, 4, 5]
collect HashMap: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
collect String: Rust
Even numbers from 1 to 20: 10
Sum from 1 to 100: 5050
float sum: 6.6
5! = 120
min: Some(1)
max: Some(9)
shortest: Some("hi")
longest: Some("hello")
for_each: 1
for_each: 2
for_each: 3
Notes
Because collect() uses type inference, you typically specify the target type via a variable type annotation (: Vec<i32>). You can also use the turbofish syntax (.collect::<Vec<i32>>()).
sum() and product() may require a type annotation. Even when the iterator yields &i32, you can resolve the type with sum::<i32>() or a variable type annotation.
For transformation and filtering adapters, see Iterator::map() / filter(). For folding and searching, see Iterator::fold() / any() / all() / find().
If you find any errors or copyright issues, please contact us.