Introduction
The all
function in Rust is a method provided by the Iterator
trait that allows you to test whether all elements of an iterator satisfy a given predicate. It returns true
if all elements match the predicate, and false
otherwise. This function is useful for checking conditions across all elements of a collection.
Syntax
The basic syntax of the all
function is as follows:
iterator.all(|item| {
// predicate logic
})
Here, iterator
is any type that implements the Iterator
trait, and |item|
is a closure that defines the predicate to be tested against each element.
Example Usage
Example 1: Checking if All Elements Are Positive
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let all_positive = numbers.iter().all(|&x| x > 0);
println!("{}", all_positive); // Output: true
}
Example 2: Checking if All Elements Are Even
fn main() {
let numbers = vec![2, 4, 6, 8];
let all_even = numbers.iter().all(|&x| x % 2 == 0);
println!("{}", all_even); // Output: true
}
Example 3: Checking If All Characters Are Alphabetic
fn main() {
let text = "Rustaceans";
let all_alphabetic = text.chars().all(|c| c.is_alphabetic());
println!("{}", all_alphabetic); // Output: true
}
Example 4: Checking If All Elements Meet a Custom Condition
fn main() {
let numbers = vec![3, 5, 7, 9];
let all_odd = numbers.iter().all(|&x| x % 2 != 0);
println!("{}", all_odd); // Output: true
}
Example 5: Checking an Empty Iterator
fn main() {
let empty: Vec<i32> = vec![];
let result = empty.iter().all(|&x| x > 0);
println!("{}", result); // Output: true
}
Considerations
- The
all
method returnstrue
for an empty iterator because there are no elements that can fail the predicate. - The iteration stops as soon as a predicate returns
false
, making the method efficient for large collections where the condition might fail early. - Ensure the closure used in
all
does not have side effects, as it may not run for all elements.
See Also
- any - Tests whether any element of an iterator matches a predicate.
- filter - Creates an iterator that only yields elements that satisfy a predicate.
- find - Searches for an element of an iterator that matches a predicate.
- fold - Reduces an iterator to a single value by applying a function.
- collect - Transforms an iterator into a collection such as a vector or hash map.