In Rust, you can find the intersection of two sets using the intersection method provided by the standard library's HashSet type.
In this example,
use std::collections::HashSet;
fn main() {
let set1: HashSet<i32> = [1, 2, 3, 4].iter().cloned().collect();
let set2: HashSet<i32> = [3, 4, 5, 6].iter().cloned().collect();
let intersection: HashSet<_> = set1.intersection(&set2).cloned().collect();
println!("Intersection of set1 and set2: {:?}", intersection);
}
Intersection of set1 and set2: {3, 4}
In this example,
use std::collections::HashSet;
fn main() {
let set1: HashSet<i32> = [1, 2, 2, 3, 4].iter().cloned().collect();
let set2: HashSet<i32> = [2, 2, 3, 4, 5].iter().cloned().collect();
let intersection: HashSet<_> = set1.intersection(&set2).cloned().collect();
println!("Intersection of set1 and set2 with duplicates: {:?}", intersection);
}
Intersection of set1 and set2 with duplicates: {2, 3, 4}
In this tutorial, we learned How to find Intersection of Two Sets in Rust language with well detailed examples.