Q:

Rust program to create a HashSet with specified capacity

belongs to collection: Rust HashSet Programs

0

In this program, we will create a HashSet with specified capacity using the with_capacity() method and print the elements of created HashSet.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to create a HashSet with specified capacity is given below. The given program is compiled and executed successfully.

// Rust program to create a HashSet 
// with specified capacity

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::with_capacity(3);
    
    set.insert(10);
    set.insert(20);
    
    println!("HashSet: {:?}", set);
    println!("Capacity of HashSet: {}",set.capacity());
}

Output:

HashSet: {10, 20}
Capacity of HashSet: 3

Explanation:

Here, we created a HashSet with capacity 3 using the with_capacity() method. Then we inserted items into HashSet. After that, we printed the HashSet and its capacity.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to demonstrate the take() method of H... >>
<< Rust program to get the capacity of HashSet...