Home »
Rust »
Rust Programs
Rust program to check a HashMap contains a specified key or not
Rust | HashMap Program: Write a program to check a HashMap contains a specified key or not.
Submitted by Nidhi, on October 17, 2021
Problem Solution:
In this program, we will create a HashMap and insert some items into it. Then we check a HashMap contains a specified key or not.
Program/Source Code:
The source code to check a HashMap contains a specified key or not is given below. The given program is compiled and executed successfully.
// Rust program to check a HashMap
// contains a specified key or not
use std::collections::HashMap;
fn main()
{
let mut map = HashMap::new();
let mut key:&str="Key1";
map.insert("Key1", 101);
map.insert("Key2", 102);
map.insert("Key3", 103);
map.insert("Key4", 104);
if map.contains_key(&key)
{
println!("Key '{}' is available in HashMap",key);
}
else
{
println!("Key {} is available in HashMap",key);
}
}
Output:
Key 'Key1' is available in HashMap
Explanation:
Here, we created a HashMap. Then we inserted some items into it. After that, we checked a specified key exists in HashMap or not, and we printed the appropriate message.
Rust HashMap Programs »