Calculate the difference between two sets
Rust Programming Language
Problem
Rust program that calculates the difference between two sets.
Input
use std::collections::HashSet;fn main() {// Create two sets of integerslet set1: HashSet<i32> = [1, 2, 3, 4, 5].iter().cloned().collect();let set2: HashSet<i32> = [2, 4].iter().cloned().collect();// Calculate the difference between set1 and set2let diff = set1.difference(&set2).cloned().collect::<HashSet<_>>();// Print out the differenceprintln!("The difference between set1 and set2 is: {:?}", diff);}{codeBox}
Output
The difference between set1 and set2 is: {1, 3, 5}{codeBox}
Explanation
In this example, we create two sets of integers using the HashSet data structure. We use the iter and cloned methods to convert arrays of integers into iterators of integer references, and then into cloned iterators of integers, which we can collect into sets.
We then calculate the difference between set1 and set2 using the difference method, which returns an iterator over the elements in the first set that are not in the second set. We use the cloned method to convert the iterator of integer references into an iterator of cloned integers, and then the collect method to collect the iterator into a new HashSet.
Finally, we print out the difference between set1 and set2 using println! and the {:?} format specifier, which formats the set using the Debug trait and displays it with curly braces.
The difference between set1 and set2. The result is a new set that contains the elements in set1 that are not in set2, which are 1, 3, and 5.