home ~ projects ~ socials

Check If A Value Is In A Vec In Rust

fn main() {
  let items = vec!["alfa", "bravo", "charlie"];
  if items.contains(&"alfa") {
    println!("found it");
  } else {
    println!("it's missing");
  }
}
Output:
found it

Alternative Method

The above doesn't work in every case (e.g. if it's a Vec<String> looking for a &str.

An alternate approach it to use .any() to look for matches:

fn main() {
  let items = vec![
    "alfa".to_string(), 
    "bravo".to_string()
  ];
  if items.iter().any(|item| {
    item == "alfa"
  }) {
    println!("found it");
  } else {
    println!("it's missing");
  }
}
Output:
found it
-- end of line --

References