Home »
Rust »
Rust Programs
Rust program to find the intersection of two HashSets
Rust | HashSet Example: Write a program to find the intersection of two HashSets.
Submitted by Nidhi, on October 13, 2021
Problem Solution:
In this program, we will create two HashSets to store integer items, and then we will find the intersection of both sets and print the result.
Program/Source Code:
The source code to find the intersection of two HashSets is given below. The given program is compiled and executed successfully.
// Rust program to find the
// intersection of two HashSets
use std::collections::HashSet;
fn main() {
let set1: HashSet<_> = [10, 15, 30, 20,12].iter().cloned().collect();
let set2: HashSet<_> = [10, 15, 20,40].iter().cloned().collect();
println!("Intersection of set1 and set2:");
for item in set1.intersection(&set2) {
print!("{} ", item);
}
}
Output:
Intersection of set1 and set2:
20 10 15
Explanation:
Here we created two HashSets to store integer elements. Then we found the intersection of both sets using the intersection() method. After that, we printed the result.
Rust HashSet Programs »