( Back to 34-Tutorial-HashMap-onwards.md )
We can use the intersection()
method to find the intersection between two sets. For example,
use std::collections::HashSet;
fn main() {
let hashset1 = HashSet::from([2, 7, 8]);
let hashset2 = HashSet::from([1, 2, 7]);
// Intersection of hashsets
let result: HashSet<_> = hashset1.intersection(&hashset2).collect();
println!("hashset1 = {:?}", hashset1);
println!("hashset2 = {:?}", hashset2);
println!("intersection = {:?}", result);
}
This code was already added to the main.rs
file in programiz/attempt-01
code to compile:
(from Rust-Start folder in git bash)
rustc programiz/attempt-01/main.rs
code to run
programiz/attempt-01/main.exe
hashset1 = {2, 7, 8}
hashset2 = {1, 2, 7}
intersection = {2, 7}
Key point above here seems to be
the line
intersection = {2, 7}
in output,
which seems to be
The intersection HashSet
We can use the difference()
method to find the difference between two sets. For example,
use std::collections::HashSet;
fn main() {
let hashset1 = HashSet::from([1, 2, 3, 4]);
let hashset2 = HashSet::from([4, 3, 2]);
// Difference between hashsets
let result: HashSet<_> = hashset1.difference(&hashset2).collect();
println!("hashset1 = {:?}", hashset1);
println!("hashset2 = {:?}", hashset2);
println!("difference = {:?}", result);
}
hashset1 = {4, 1, 2, 3}
hashset2 = {4, 3, 2}
difference = {1}
We can use the symmetric_difference()
method to find the symmetric difference between two sets. The symmetric difference returns values from both sets except the ones in both.
use std::collections::HashSet;
fn main() {
let hashset1 = HashSet::from([2, 7, 8]);
let hashset2 = HashSet::from([1, 2, 7, 9]);
// Symmetric difference of hashsets
let result: HashSet<_> = hashset1.symmetric_difference(&hashset2).collect();
println!("hashset1 = {:?}", hashset1);
println!("hashset2 = {:?}", hashset2);
println!("symmetric difference = {:?}", result);
}
hashset1 = {7, 2, 8}
hashset2 = {2, 9, 7, 1}
symmetric difference = {8, 9, 1}