Skip to main content

How to Check if Any Item Matches in Rust with any

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

ages.iter().any(|age| *age >= 65) is true when at least one item makes the closure return true, and false otherwise. It stops at the first match, and for an empty Vec it's false.

Syntax​

Syntax
<collection>.iter().any(|<item>| <condition>)
PartWhat it does
<collection>.iter()An iterator over the items of a collection, such as a Vec. any is a method of iterators, not of Vec.
|<item>|Each item in turn. With iter(), it's a reference to the item, such as a &i32.
<condition>A bool expression about the item, such as *age >= 65, where * reads the value the reference points to.
The resulttrue as soon as one item gives true. false when none does, and for an empty collection.

The standard library's Iterator::any: "Tests if any element of the iterator matches a predicate." It adds: "any() is short-circuiting; in other words, it will stop processing as soon as it finds a true, given that no matter what else happens, the result will also be true." And: "An empty iterator returns false."

The Example​

The example checks a list of roles for one that starts with beta, a list of ages for someone of 65 or over and for a child under 12, and an empty list for a number above zero. Then a changed version compares an age without the *.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project and Write the Code​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, which makes a Vec of the roles customer and beta-tester and a Vec of the ages 34, 15 and 70, prints whether any role starts with beta, whether any age is at least 65 and whether any is under 12, and whether any number in an empty Vec is above zero.

src/main.rs
fn main() {
let roles = vec!["customer", "beta-tester"];
let ages = vec![34, 15, 70];

println!("{}", roles.iter().any(|role| role.starts_with("beta")));
println!("{}", ages.iter().any(|age| *age >= 65));
println!("{}", ages.iter().any(|age| *age < 12));

let empty: Vec<i32> = Vec::new();
println!("{}", empty.iter().any(|n| *n > 0));
}
  • role.starts_with("beta") is true for a role whose text begins with beta.
  • *age >= 65: iter() gives each age as a reference, a &i32, and *age is the number it points to.
  • let empty: Vec<i32> = Vec::new(); makes a Vec with no items, so any has nothing to test.

Step 2: Run It​

Terminal
cargo run -q
Output
true
true
false
false

-q keeps Cargo quiet, so only the program's output shows. The command is the same in zsh, bash and PowerShell.

Step 3: Compare an Age Without the Asterisk​

Replace src/main.rs with a version whose second check compares age with 65 directly:

src/main.rs
fn main() {
let roles = vec!["customer", "beta-tester"];
let ages = vec![34, 15, 70];

println!("{}", roles.iter().any(|role| role.starts_with("beta")));
println!("{}", ages.iter().any(|age| age >= 65));
println!("{}", ages.iter().any(|age| *age < 12));

let empty: Vec<i32> = Vec::new();
println!("{}", empty.iter().any(|n| *n > 0));
}
Terminal
cargo run -q
Output
error[E0308]: mismatched types
--> src/main.rs:6:49
|
6 | println!("{}", ages.iter().any(|age| age >= 65));
| ^^ expected `&_`, found integer
|
= note: expected reference `&_`
found type `{integer}`
help: consider dereferencing the borrow
|
6 | println!("{}", ages.iter().any(|age| *age >= 65));
| +

For more information about this error, try `rustc --explain E0308`.
error: could not compile `demo` (bin "demo") due to 1 previous error

A zsh terminal where cargo run -q prints true, true, false and false, then, for the changed file, fails with error E0308, mismatched types, expected a reference, found integer, with a help that suggests dereferencing the borrow.

What Happened​

  • true: beta-tester starts with beta.
  • true: 70 is 65 or over.
  • false: no age is under 12.
  • false: the empty Vec has no item that could match.
  • The changed version didn't compile. age is a reference and 65 is a number, so Rust said "expected &_, found integer". The help, "consider dereferencing the borrow", adds the *.

Common Mistakes​

MistakeWhat happensDo this instead
Calling any on the Vec itself, as in ages.any(...)error[E0599]: no method named `any` found for struct `Vec<{integer}>` in the current scopeCall .iter() first
Comparing a text item with == and no *, as in roles.iter().any(|role| role == "customer")error[E0277]: can't compare `&str` with `str`Write *role == "customer", or use roles.contains(&"customer")
Expecting any to say which item matchedIt gives only true or falseUse position: it gave Some(2) for the age of 65 or over, the third item, and None when nothing matched

Troubleshooting​

SymptomLikely causeFix
expected `&_`, found integerThe reference from iter() is compared with a numberAdd *, as in *age >= 65
An empty list gives false with any but true with allany asks whether one item passes, and all whether no item failsCheck is_empty() first when an empty list needs its own answer

FAQ​

Does any check every item?​

No, it stops at the first match. In my check, a closure that printed each age before testing it printed only checking 70 for the ages 70, 15 and 34, and any returned true.

What's the difference between any and all?​

any is true when at least one item matches, and all when every item does. For the ages 34, 15 and 70, all(|age| *age >= 18) gave false, because 15 is under 18, and all(|age| *age > 0) gave true. For an empty list, all gave true: its documentation says "An empty iterator returns true."

How do I check whether a Vec holds one exact value?​

With contains: roles.contains(&"customer") gave true. any is for a condition, such as starts_with("beta").

Conclusion​

iter().any(|item| condition) tells you whether at least one item matches, stopping at the first match and returning false for an empty collection. Remember that iter() hands the closure references, so compare with *item.

Additional Resources​