Introduction
The
any
function in Rust is an iterator adapter that checks if any element of an iterator satisfies a given predicate. This function is useful when you need to determine if at least one element in a collection meets certain criteria.
Syntax
iterator.any(|element| condition)
The
any
function takes a closure that returns a boolean value. It returns
true
if the closure returns
true
for any element, and
false
otherwise.
Example Usage
Example 1: Checking for Any Even Numbers
fn main() {
let numbers = vec![1, 3, 5, 7, 9];
let has_even = numbers.into_iter().any(|x| x % 2 == 0);
println!("{}", has_even); // Output: false
}
Example 2: Checking for a Specific String
fn main() {
let words = vec!["apple", "banana", "cherry"];
let contains_banana = words.into_iter().any(|word| word == "banana");
println!("{}", contains_banana); // Output: true
}
Example 3: Checking for Any Negative Numbers
fn main() {
let numbers = vec![10, 20, -30, 40];
let has_negative = numbers.into_iter().any(|x| x < 0);
println!("{}", has_negative); // Output: true
}
Example 4: Checking for Any Empty Strings
fn main() {
let strings = vec!["hello", "world", ""];
let has_empty = strings.into_iter().any(|s| s.is_empty());
println!("{}", has_empty); // Output: true
}
Example 5: Checking for Any True Values in a Boolean Vector
fn main() {
let bools = vec![false, false, true, false];
let has_true = bools.into_iter().any(|b| b);
println!("{}", has_true); // Output: true
}
Considerations
- The
any
function short-circuits, meaning it stops processing as soon as it finds an element that satisfies the predicate.
- Using
any
on an empty iterator will always return false
.
- Ensure the closure used in
any
does not have side effects, as it may not run for all elements.
See Also
- all - Checks if all elements of an iterator satisfy a predicate.
- find - Searches for the first element that satisfies a predicate and returns it.
- position - Returns the index of the first element that satisfies a predicate.
- filter - Creates an iterator that only yields elements that satisfy a predicate.
- enumerate - Creates an iterator that yields pairs of the index and the element.