ADVERTISEMENT
ADVERTISEMENT

Rust program to check an item contains in HashSet or not

Rust | HashSet Example: Write a program to check an item contains in HashSet or not.
Submitted by Nidhi, on October 26, 2021

Problem Solution:

In this program, we will read an integer item from the user then we will check an item is available in HashSet or not.

Program/Source Code:

The source code to check an item contains in HashSet or not is given below. The given program is compiled and executed successfully.

// Rust program to check an item contains
// in HashSet or not

use std::collections::HashSet;
use std::io;

fn main() {
    let mut set:HashSet<i32> = HashSet::new();
    let mut item:i32=0;
    let mut input = String::new();

    set.insert(10);
    set.insert(20);
    set.insert(30);
    set.insert(40);
    set.insert(50);
    
    println!("HashSet: \n{:?}",set);
    
    println!("Enter Item: ");
    io::stdin().read_line(&mut input).expect("Not a valid string");
    item = input.trim().parse().expect("Not a valid number");
    
    if(set.contains(&item))
    {
        println!("Item {} is available in HashSet",item);
    }
    else
    {
        println!("Item {} is not available in HashSet",item);
    }
}

Output:

HashSet: 
{20, 40, 50, 30, 10}
Enter Item: 
30
Item 30 is available in HashSet

Explanation:

Here, we created a HashSet to store integer elements. Then we added items using the insert() method. After that, we read an item from the user and check an item exists in HashSet or not, and print the appropriate message.

Rust HashSet Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.