w3resource

Rust Set Union Function

Rust Arrays: Exercise-2 with Solution

Write a Rust function that takes two sets as input and returns a new set containing all unique elements from both input sets.

Sample Solution:

Rust Code:

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

// Define a function to find the union of two sets
fn find_union(set1: &HashSet<i32>, set2: &HashSet<i32>) -> HashSet<i32> {
    // Create a new HashSet to store the union of the input sets
    let mut union_set = HashSet::new(); // New HashSet to store the union elements

    // Iterate over each element in the first set and insert it into the union set
    for &element in set1 {
        union_set.insert(element);
    }

    // Iterate over each element in the second set and insert it into the union set
    for &element in set2 {
        union_set.insert(element);
    }

    // Return the union set containing all unique elements from both input sets
    union_set // Return the union set containing all unique elements from both input sets
}

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

    // Find the union of the two sets
    let union = find_union(&set1, &set2);

    // Print the union set
    println!("Union set: {:?}", union); // Print the union set
}

Output:

Union set: {5, 3, 4, 1, 2}

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 find_union(set1: &HashSet<i32>, set2: &HashSet<i32>) -> HashSet<i32> { ... }: This line defines a function named "find_union()" that takes two sets (HashSet<i32>) as input references and returns a new set containing all unique elements from both input sets.
  • The "find_union()" function iterates over each element in the input sets and inserts them into a new set, ensuring uniqueness.
  • 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 with integer elements.
  • The "find_union()" function is called with the two sample sets as input, and the resulting union set is printed to the console.

Rust Code Editor:

Previous: Rust Set Intersection Function.
Next: Rust Set Difference 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.