To check if a specific item is present in a Set in Rust, you can use the contains
method.
In this example,
my_set
containing elements of a specific type.contains
method of the HashSet to check if a specific item is present.contains
method returns true
if the item is present in the HashSet, otherwise it returns false
.use std::collections::HashSet;
fn main() {
// Define HashSet with items
let mut my_set = HashSet::new();
my_set.insert("apple");
my_set.insert("banana");
my_set.insert("orange");
my_set.insert("grape");
my_set.insert("melon");
// Check if item is present
let item = "banana";
let is_present = my_set.contains(item);
// Print result
println!("Is {} present in the Set? {}", item, is_present);
}
Is banana present in the Set? true
In this example,
my_set
containing elements of a specific type.contains
method of the HashSet to check if a specific item is not present.contains
method returns false
if the item is not present in the HashSet.use std::collections::HashSet;
fn main() {
// Define HashSet with items
let mut my_set = HashSet::new();
my_set.insert("apple");
my_set.insert("banana");
my_set.insert("orange");
my_set.insert("grape");
my_set.insert("melon");
// Check if item is not present
let item = "peach";
let is_not_present = !my_set.contains(item);
// Print result
println!("Is {} not present in the Set? {}", item, is_not_present);
}
Is peach not present in the Set? true
In this tutorial, we learned How to check if a Specific Item is present in the Set in Rust language with well detailed examples.