w3resource

Rust Set Conversion Function

Rust Arrays: Exercise-7 with Solution

Write a Rust function that converts a vector of elements into a set.

Sample Solution:

Rust Code:

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

// Define a function to convert a vector into a set
fn vector_to_set<T: Eq + std::hash::Hash + Clone>(vector: Vec<T>) -> HashSet<T> {
    let mut set = HashSet::new(); // Create an empty HashSet to store elements

    // Iterate over each element in the vector
    for element in vector {
        set.insert(element); // Insert the element into the HashSet
    }

    set // Return the resulting HashSet
}

fn main() {
    // Create a sample vector
    let vector = vec![1, 2, 3, 4, 5, 3, 2, 1];

    // Convert the vector into a set
    let set = vector_to_set(vector);

    // Print the resulting set
    println!("Set: {:?}", set);
}

Output:

Set: {2, 3, 4, 1, 5}

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 vector_to_set<T: Eq + std::hash::Hash + Clone>(vector: Vec<T>) -> HashSet<T> { ... }: This line defines a generic function named vector_to_set that takes a vector (Vec<T>) of elements of any type 'T' that implements the 'Eq', 'Hash', and 'Clone' traits. It returns a HashSet<T> containing unique elements from the input vector.
  • The "vector_to_set()" function creates an empty 'HashSet' to store elements. Then, it iterates over each element in the input vector and inserts it into the 'HashSet'. This ensures that only unique elements are retained in the set.
  • The "main()" function serves as the entry point of the program. It creates a sample vector and calls the "vector_to_set()" function to convert the vector into a set. Finally, it prints the resulting set.

Rust Code Editor:

Previous: Rust Check Superset Function.
Next: Rust HashMap Iteration: Printing Key-Value pairs.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-7.php