Suppose we have an array or vector of values, and we want to see if a specific value is present in it. A for
-loop could be used, but this requires several lines of code.
Instead, we can use iter()
and invoke the any()
function. This receives a higher-order function, and we can use it to see if the element exists.
To call Any()
, we must have an iterator. If we have an array or vector, we can use the iter()
function to get an iterator.
any()
function returns true or false. This makes it simple to call in many places in a program.fn main() { // Test array with any. let values = ["bird", "frog", "dog", "cat"]; if values.iter().any(|&e| e == "dog") { println!("DOG WAS FOUND"); } if !values.iter().any(|&e| e == "lizard") { println!("LIZARD WAS NOT FOUND"); } // Test vector. let test = vec!["abc", "", "DEF"]; if test.iter().any(|&e| e.is_empty()) { println!("EMPTY ELEMENT FOUND"); } }DOG WAS FOUND LIZARD WAS NOT FOUND EMPTY ELEMENT FOUND
Does calling the any()
function cause any slowdown in Rust programs? This can be quickly tested in an example benchmark program.
any()
function to search the vector for an element matching X.for
-loop over the same vector, and we make sure to break
when we find the matching element.any()
for this kind of logic.use std::time::*; fn main() { if let Ok(max) = "10000".parse::<usize>() { let mut count = 0; let mut values = vec![]; for _ in 0..1000 { values.push("?"); } values[500] = "X"; // Version 1: use any. let t0 = Instant::now(); for _ in 0..max { if values.iter().any(|&e| e == "X") { count += 1; } } println!("{} ms", t0.elapsed().as_millis()); // Version 2: use for-loop with break. let t1 = Instant::now(); for _ in 0..max { for &v in &values { if v == "X" { count += 1; break; } } } println!("{} ms", t1.elapsed().as_millis()); println!("{count}"); } }4 ms any 4 ms for, break 20000
Functions like any()
have sometimes been provided in languages, but have involved worse performance than for
-loops. In Rust this does not appear to be the situation.
any()
function is a good choice for searching a vector or array.contains()
function. This may be a better option than calling any()
to find a specific value.There is no contains()
function on an iterator. But the any()
function can be used to implement "contains" with a small function argument.