In Rust, you can access items in a set using iteration or specific methods provided by the HashSet data structure.
In this example,
string_set
containing strings.use std::collections::HashSet;
fn main() {
let mut string_set = HashSet::new();
string_set.insert("Apple");
string_set.insert("Banana");
string_set.insert("Orange");
string_set.insert("Grapes");
for item in &string_set {
println!("{:?}", item);
}
}
Apple Banana Orange Grapes
In this example,
number_set
containing integers.len()
method to get the number of elements in the set.contains()
method to check if an item exists in the set.use std::collections::HashSet;
fn main() {
let mut number_set = HashSet::new();
number_set.insert(1);
number_set.insert(2);
number_set.insert(3);
number_set.insert(4);
println!("Number of elements: {:?}", number_set.len());
println!("Does set contain 3? {:?}", number_set.contains(&3));
}
Number of elements: 4 Does set contain 3? true
In this tutorial, we learned How to Access Items in a Set in Rust language with well detailed examples.