w3resource

Rust Set Cardinality Function

Rust Arrays: Exercise-8 with Solution

Write a Rust function that returns the number of elements in a set.

Sample Solution:

Rust Code:

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

// Define a function to get the number of elements in a set
fn count_elements<T>(set: &HashSet<T>) -> usize {
    set.len() // Return the number of elements in the set
}

fn main() {
    // Create a sample set
    let mut set = HashSet::new();
    set.insert(1);
    set.insert(2);
    set.insert(3);

    // Get the number of elements in the set
    let count = count_elements(&set);

    // Print the count of elements in the set
    println!("Number of elements in the set: {}", count);
}

Output:

Number of elements in the set: 3

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 count_elements<T>(set: &HashSet<T>) -> usize { ... }: This line defines a generic function named count_elements that takes a reference to a set (&HashSet<T>) of elements of any type 'T'. It returns the number of elements in the set as a 'usize'.
  • The "count_elements()" function simply returns the result of calling the "len()" method on the set, which gives us the number of elements in the set.
  • The "main()" function serves as the entry point of the program. It creates a sample set, calls the "count_elements()" function to get the number of elements in the set, and prints the count.

Rust Code Editor:

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