Introduction
The
count
function in Rust is an iterator adapter that consumes the iterator and returns the number of elements it contains. This function is useful when you need to determine the size of an iterator's output.
Syntax
iterator.count()
The
count
function takes no arguments and returns a
usize
indicating the number of elements in the iterator.
Example Usage
Example 1: Counting Elements in a Vector
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let count = numbers.iter().count();
println!("{}", count); // Output: 5
}
Example 2: Counting Elements in a Range
fn main() {
let range = 1..10;
let count = range.count();
println!("{}", count); // Output: 9
}
Example 3: Counting Elements in a Filtered Iterator
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let count = numbers.iter().filter(|&&x| x % 2 == 0).count();
println!("{}", count); // Output: 5
}
Example 4: Counting Elements in a String Vector
fn main() {
let words = vec!["apple", "banana", "cherry"];
let count = words.iter().count();
println!("{}", count); // Output: 3
}
Example 5: Counting Characters in a String
fn main() {
let s = "hello";
let count = s.chars().count();
println!("{}", count); // Output: 5
}
Considerations
- The
count
function consumes the iterator, meaning it cannot be used again after calling count
.
- Using
count
on an infinite iterator will result in an infinite loop.
- For some collections (e.g. linked lists), counting elements may be an O(n) operation as it needs to iterate through each element.
See Also
- filter - Creates an iterator that only yields elements that satisfy a predicate.
- map - Transforms each element of an iterator using a function.
- chain - Combines two iterators into a single iterator.
- collect - Transforms an iterator into a collection.