9716278
9716278

Reputation: 2404

How do I check if a thing is in a vector

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.

Upvotes: 127

Views: 125535

Answers (2)

8176135
8176135

Reputation: 4133

There is the contains (https://doc.rust-lang.org/std/vec/struct.Vec.html#method.contains) method on Vec.

Example:

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

if n.contains(&"-i") { 
    println!("yes");
} else {
    println!("no");
}

It is somewhat restrictive, for instance it doesn't allow checking if a Vec<String> contains x if x is of type &str. In that case, you will have to use the .iter().any(...) method described by @harmic

Upvotes: 156

harmic
harmic

Reputation: 30597

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.

Upvotes: 118

Related Questions