To initialize a set in Rust, you can use the HashSet struct from the std::collections module.
In this example,
use std::collections::HashSet
.my_set
using the HashSet::new()
method.my_set
using the insert
method.use std::collections::HashSet;
fn main() {
// Declare and initialize a set
let mut my_set: HashSet<&str> = HashSet::new();
// Add initial elements to the set
my_set.insert("apple");
my_set.insert("banana");
my_set.insert("orange");
// my_set now contains "apple", "banana", and "orange"
// Example usage:
// Add an element to the set
my_set.insert("kiwi");
// Remove an element from the set
my_set.remove("banana");
// Check if an element is present in the set
let contains_element = my_set.contains("apple");
println!("Is element 'apple' present in the set: {}", contains_element);
}
Is element 'apple' present in the set: true
In this example,
use std::collections::HashSet
.empty_set
using the HashSet::new()
method.HashSet::new()
method initializes an empty set that is ready to be used for storing unique elements.empty_set
using set operations such as adding elements, removing elements, and checking for membership.use std::collections::HashSet;
fn main() {
// Declare and initialize an empty set
let mut empty_set: HashSet<&str> = HashSet::new();
// empty_set is now initialized as an empty set
// Example usage:
// Add elements to the set
empty_set.insert("apple");
// Remove elements from the set
empty_set.remove("apple");
// Check if an element is present in the set
let contains_element = empty_set.contains("apple");
println!("Is element 'apple' present in the set: {}", contains_element);
}
Is element 'apple' present in the set: false
In this tutorial, we learned How to Initialize a Set in Rust language with well detailed examples.