Rust program to create a HashSet with specified capacity

Rust | HashSet Example: Write a program to create a HashSet with specified capacity.
Submitted by Nidhi, on October 13, 2021

Problem Solution:

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

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.

Rust HashSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.