Yes, in Rust, you can use a HashSet or BTreeSet to store a collection of unique values, similar to a Python set. These sets do not require key-value pairs like a HashMap and are used to store unique elements.
Using HashSet
HashSet is the most common choice for a set of unique values. It uses a hash table for storage, providing average O(1) time complexity for insertions, deletions, and lookups.
Here's how you can initialize and use a HashSet in Rust:
use std::collections::HashSet;
fn main() {
// Initialize a HashSet with some values
let mut my_set: HashSet<i32> = HashSet::new();
my_set.insert(1);
my_set.insert(2);
my_set.insert(3);
// Print the set
println!("{:?}", my_set); // Output: {1, 2, 3}
// Check if a value is in the set
if my_set.contains(&2) {
println!("Set contains 2");
}
// Remove a value from the set
my_set.remove(&2);
println!("{:?}", my_set); // Output: {1, 3}
}
Using BTreeSet
BTreeSet is an alternative that uses a balanced binary tree for storage. It provides O(log n) time complexity for insertions, deletions, and lookups, and keeps the elements sorted.
Here's how you can initialize and use a BTreeSet in Rust:
use std::collections::BTreeSet;
fn main() {
// Initialize a BTreeSet with some values
let mut my_set: BTreeSet<i32> = BTreeSet::new();
my_set.insert(1);
my_set.insert(2);
my_set.insert(3);
// Print the set
println!("{:?}", my_set); // Output: {1, 2, 3}
// Check if a value is in the set
if my_set.contains(&2) {
println!("Set contains 2");
}
// Remove a value from the set
my_set.remove(&2);
println!("{:?}", my_set); // Output: {1, 3}
}
Initializing a Set with Values
You can also initialize a HashSet or BTreeSet directly with values using the collect method:
use std::collections::HashSet;
fn main() {
let initial_data = vec![1, 2, 3];
let my_set: HashSet<_> = initial_data.into_iter().collect();
println!("{:?}", my_set); // Output: {1, 2, 3}
}
Or using the from method:
use std::collections::HashSet;
fn main() {
let my_set: HashSet<_> = HashSet::from([1, 2, 3]);
println!("{:?}", my_set); // Output: {1, 2, 3}
}
Summary
HashSet: Best for most use cases where you need a set of unique values with average O(1) performance.
BTreeSet: Useful when you need the elements to be sorted and can tolerate O(log n) performance.
Both HashSet and BTreeSet provide functionality similar to Python's set, allowing you to store unique values without the need for key-value pairs.