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.
You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.
We can find the index of an element in a vector using the std::find_if() function. This function finds the first element in a range for which the predicate function returns true.
%in% operator can be used in R Programming Language, to check for the presence of an element inside a vector. It returns a boolean output, evaluating to TRUE if the element is present, else returns false.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With