I reckon that there is contains_key() method for this purpose, but I am getting error as I want to use Some and None which has boolean as return value. get() method works fine for the opposite state which is finding a value that corresponds to a key. The main goal is to create an endpoint for finding a key by value and the opposite. I have come up to the following logic for finding the value but am stuck with finding the key:
fn main() {
use std::collections::HashMap;
let mut my_info: HashMap<String, String> = HashMap::new();
my_info.insert("Brad".to_string(), "Pitt".to_string());
my_info.insert("Tom".to_string(), "Cruise".to_string());
match my_info.get("Brad") {
Some(firstname) => println!("Last Name: {}", firstname),
None => println!("FIRST NAME NOT FOUND")
}
}
CodePudding user response:
You cannot do that directly. HashMap
s are all about going from a key
to a value
. What you can do here, is to have two HashMap
s, one for key
to value
and the other for value
to key
. Note: this means that the key
and value
will be independent and change in one will not change the other. Moreover, it means that they will be different objects which can double your memory usage / take a lot of time / might not be possible. You will also need both the key
and value
to be unique and hashable. The code can be something like this:
struct BiMap<K, V> {
key_val: HashMap<K, V>,
val_key: HashMap<V, K>
}
impl<K, V> BiMap<K, V> {
pub fn get_by_key(&self, key: &K) -> Option<V> {
self.key_val.get(key)
}
pub fn get_by_val(&self, val: &V) -> Option<K> {
self.val_key.get(val)
}
}
(There are very likely some type errors there. Follow the compiler messages / Hashmap::get
's signature to fix them.)
Another way, if you cannot do the above / do not want to do the above, is to iterate through the whole hashmap, comparing the values and returning the key when you find it. The code will be somewhat like this:
my_info.iter().find(|(_, v)| v == last_name).map(|(first_name, _)| first_name)
This will give you the first_name
of the first person to have the last_name
specified.
CodePudding user response:
There's a crate for bi-directional maps: https://docs.rs/bidirectional-map/0.1.0/bidirectional_map/