w3resource

Rust Set Operations with Iterators

Rust Arrays: Exercise-10 with Solution

Write a Rust function that performs set operations (intersection, union, difference, etc.) using iterators and returns the result as a new set.

Sample Solution:

Rust Code:

use std::collections::HashSet; // Import the HashSet type from the standard library

// Define a function to perform set operations using iterators
fn perform_set_operation<T: Eq + std::hash::Hash + Clone>(
    set1: &HashSet<T>, // First input set
    set2: &HashSet<T>, // Second input set
    operation: char,   // Operation to perform ('u' for union, 'i' for intersection, 'd' for difference, 's' for symmetric difference)
) -> HashSet<T> {
    // Match the operation character
    match operation {
        'u' => set1.union(set2).cloned().collect(),               // Union
        'i' => set1.intersection(set2).cloned().collect(),        // Intersection
        'd' => set1.difference(set2).cloned().collect(),          // Difference (elements in set1 but not in set2)
        's' => set1.symmetric_difference(set2).cloned().collect(), // Symmetric Difference (elements in set1 or set2 but not in both)
        _ => HashSet::new(),                                      // Default to an empty set if an invalid operation is provided
    }
}

fn main() {
    // Create two sample sets
    let set1: HashSet<i32> = vec![1, 2, 3].into_iter().collect();
    let set2: HashSet<i32> = vec![3, 4, 5].into_iter().collect();

    // Perform set operations and print the results
    println!("Union: {:?}", perform_set_operation(&set1, &set2, 'u'));
    println!("Intersection: {:?}", perform_set_operation(&set1, &set2, 'i'));
    println!("Difference: {:?}", perform_set_operation(&set1, &set2, 'd'));
    println!("Symmetric Difference: {:?}", perform_set_operation(&set1, &set2, 's'));
}

Output:

Union: {2, 1, 3, 5, 4}
Intersection: {3}
Difference: {1, 2}
Symmetric Difference: {5, 2, 1, 4}

Explanation:

Here is a brief explanation of the above Rust code:

  • use std::collections::HashSet;: Imports the "HashSet" type from the standard library, allowing us to use sets in our code.
  • fn perform_set_operation<T: Eq + std::hash::Hash + Clone>(set1: &HashSet<T>, set2: &HashSet<T>, operation: char) -> HashSet<T> { ... }: Defines a generic function named perform_set_operation that takes two sets (HashSet<T>) as input references, an operation character (char), and returns a new set (HashSet<T>) as the result of the set operation. The function requires that the type T implements the 'Eq', 'Hash', and 'Clone' traits.
  • The "perform_set_operation()" function matches the provided operation character to perform set operations using iterators:
    • 'u' for union
    • 'i' for intersection
    • 'd' for difference
    • 's' for symmetric difference If an invalid operation character is provided, it returns an empty set.
  • The "main()" function serves as the entry point of the program. It creates two sample sets ('set1' and 'set2'), performs various set operations (union, intersection, difference, symmetric difference) using the "perform_set_operation()" function, and prints the results.

Rust Code Editor:

Previous: Rust Set Equality Function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.