rust check if key in hashmap
To check if a key exists in a HashMap in Rust, you can use the contains_key
method. Here's an example:
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key1", "value1");
map.insert("key2", "value2");
let key = "key1";
if map.contains_key(key) {
println!("The key '{}' exists in the HashMap.", key);
} else {
println!("The key '{}' does not exist in the HashMap.", key);
}
}
In this example, we create a new HashMap called map
and insert two key-value pairs into it. We then define a variable key
and check if it exists in the HashMap using the contains_key
method. If the key exists, we print a message indicating that it exists. Otherwise, we print a message indicating that it does not exist.
You can replace "key1"
with any key you want to check in the HashMap.