To create a set of sets in Rust, you can use the HashSet
from the std::collections
module. Each inner set can also be a HashSet
.
In this example,
use std::collections::HashSet;
at the top of your code file. This allows you to use the HashSet
type.HashSet
named set_of_sets
, where each element is another HashSet
. This is done by declaring let mut set_of_sets: HashSet> = HashSet::new();
.let set1: HashSet = [1, 2, 3].iter().cloned().collect();
initializes a set containing the integers 1, 2, and 3.let set2: HashSet = [4, 5, 6].iter().cloned().collect();
.insert
method: set_of_sets.insert(set1);
and set_of_sets.insert(set2);
.for
loop for this: for inner_set in &set_of_sets
followed by for item in inner_set
.use std::collections::HashSet;
fn main() {
// Step 1: Create the outer set of sets
let mut set_of_sets: HashSet<HashSet<i32>> = HashSet::new();
// Step 2: Create inner sets
let set1: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
let set2: HashSet<i32> = [4, 5, 6].iter().cloned().collect();
// Step 3: Add inner sets to the outer set
set_of_sets.insert(set1);
set_of_sets.insert(set2);
// Step 4: Iterate and print the elements of each inner set
for inner_set in &set_of_sets {
println!("Inner set:");
for item in inner_set {
print!("{} ", item);
}
println!("");
}
}
Inner set: 1 2 3 Inner set: 4 5 6
In this example,
use std::collections::HashSet;
at the top of your code file. This allows you to use the HashSet
type.HashSet
named set_of_sets
, where each element is another HashSet
. This is done by declaring let mut set_of_sets: HashSet> = HashSet::new();
.let set1: HashSet = ["apple", "banana"].iter().cloned().collect();
initializes a set containing the strings "apple" and "banana".let set2: HashSet = ["cherry", "date"].iter().cloned().collect();
.insert
method: set_of_sets.insert(set1);
and set_of_sets.insert(set2);
.for
loop for this: for inner_set in &set_of_sets
followed by for item in inner_set
.use std::collections::HashSet;
fn main() {
// Step 1: Create the outer set of sets
let mut set_of_sets: HashSet<HashSet<String>> = HashSet::new();
// Step 2: Create inner sets
let set1: HashSet<String> = ["apple", "banana"].iter().cloned().collect();
let set2: HashSet<String> = ["cherry", "date"].iter().cloned().collect();
// Step 3: Add inner sets to the outer set
set_of_sets.insert(set1);
set_of_sets.insert(set2);
// Step 4: Iterate and print the elements of each inner set
for inner_set in &set_of_sets {
println!("Inner set:");
for item in inner_set {
print!("{} ", item);
}
println!("");
}
}
Inner set: apple banana Inner set: cherry date
In this tutorial, we learned How to create a Set of Sets in Rust language with well detailed examples.