Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

rust - 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.

question from:https://stackoverflow.com/questions/58368801/how-do-i-check-if-a-thing-is-in-a-vector

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...