In Rust, you can copy a set (implemented using collections like HashSet) by using the clone() method or by simply assigning it to a new variable, which performs a shallow copy.
In this example,
numbers
containing some integer elements.copied_numbers
by using the clone() method with numbers
.copied_numbers
contains a copy of all elements from numbers
.use std::collections::HashSet;
fn main() {
let mut numbers = HashSet::new();
numbers.insert(1);
numbers.insert(2);
numbers.insert(3);
let copied_numbers = numbers.clone();
println!("Copied Numbers: {:?}", copied_numbers);
}
Copied Numbers: {1, 2, 3}
In this example,
fruits
containing some string elements.copied_fruits
by simply assigning fruits
to it.copied_fruits
contains a copy of all elements from fruits
.use std::collections::HashSet;
fn main() {
let mut fruits = HashSet::new();
fruits.insert("Apple");
fruits.insert("Banana");
fruits.insert("Cherry");
let copied_fruits = fruits;
println!("Copied Fruits: {:?}", copied_fruits);
}
Copied Fruits: {"Apple", "Cherry", "Banana"}
In this tutorial, we learned How to Copy a Set in Rust language with well detailed examples.