HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How do I check if a thing is in a vector

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
checkhowvectorthing

Problem

How do I check if a thing is in a vector?

let n= vec!["-i","mmmm"];
if "-i" in n {
println!("yes");
} else {
println!("no");


I'm guessing that I need to put this in a loop and then do if "-i" in x where x is the iter var. But I was hopping there is a handy method available or I've confused the syntax and there is a similar way to do this.

Solution

While you could construct a loop, an easier way would be to use the any method on an iterator for your vector.

any takes a closure that returns true or false. The closure is called for each of the items in turn until it finds one that returns true. Note that the iterator returns references to the values (thus the & in |&i|).

let n= vec!["-i","mmmm"];

if n.iter().any(|&i| i=="-i") {
    println!("Yes");
}


Since any operates on iterators, it can be used with any type of container. There are a large number of similar methods available on iterators, such as all, find, etc. See the standard library documentation for Iterators.

Code Snippets

let n= vec!["-i","mmmm"];

if n.iter().any(|&i| i=="-i") {
    println!("Yes");
}

Context

Stack Overflow Q#58368801, score: 124

Revisions (0)

No revisions yet.