In Rust, you can find the union of two sets using the union method provided by the standard library.
In this example,
set1
and set2
.union
method on set1
with set2
as an argument.union
method combines the elements of both sets into set1
.fn main() {
let mut set1 = [1, 2, 3].iter().cloned().collect::<std::collections::HashSet<_>>();
let set2 = [3, 4, 5].iter().cloned().collect::<std::collections::HashSet<_>>();
set1.extend(set2);
println!("{:?}", set1);
}
{1, 2, 3, 4, 5}
In this example,
set1
and set2
.union
method provided by the HashSet
struct to merge set2
into set1
.use std::collections::HashSet;
fn main() {
let mut set1: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
let set2: HashSet<i32> = [3, 4, 5].iter().cloned().collect();
set1.union(&set2);
println!("{:?}", set1);
}
{1, 2, 3, 4, 5}
In this tutorial, we learned How to find Union of Two Sets in Rust language with well detailed examples.