Rust Set Difference Function
Rust Arrays: Exercise-3 with Solution
Write a Rust function that takes two sets as input and returns a new set containing elements that are present in the first set but not in the second set.
Sample Solution:
Rust Code:
use std::collections::HashSet;
fn set_difference(set1: &HashSet<i32>, set2: &HashSet<i32>) -> HashSet<i32> {
let mut difference_set = HashSet::new();
for &element in set1 {
if !set2.contains(&element) {
difference_set.insert(element);
}
}
difference_set
}
fn main() {
let set1: HashSet<i32> = vec![1, 2, 3].into_iter().collect();
let set2: HashSet<i32> = vec![3, 4, 5].into_iter().collect();
let difference = set_difference(&set1, &set2);
println!("Difference set: {:?}", difference);
}
Output:
Difference set: {2, 1}
Explanation:
Here is a brief explanation of the above Rust code:
- use std::collections::HashSet;: This line imports the "HashSet" type from the standard library, allowing us to use sets in our code.
- fn set_difference(set1: &HashSet<i32>, set2: &HashSet<i32>) -> HashSet<i32> { ... }: This line defines a function named "set_difference()" that takes two sets (HashSet<i32>) as input references and returns a new set containing elements that are present in the first set but not in the second set.
- The set_difference function iterates over each element in the first input set (set1) and checks if it is not present in the second input set (set2). If an element is found in 'set1' but not in 'set2', it is inserted into the 'difference_set'.
- fn main() { ... }: This line defines the "main()" function, which is the entry point of the Rust program.
- Two sample sets 'set1' and 'set2' are created using vec![], collecting the vector elements into HashSet.
- The "set_difference()" function is called with the two sample sets as input, and the resulting difference set is stored in the 'difference' variable.
- The difference set 'difference' is printed to the console using println!.
Rust Code Editor:
Previous: Rust Set Union Function.
Next: Rust Set Symmetric Difference Function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/collections_and_data_structures/rust-sets-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics