'Check 2 keys for Vacant
I am using the HashMap to store some of the value. Now I want to check whether HashMap contains keys, if not insert data else return HashMap is not empty. Below code explain that I am checking for product id, but I want to check for 2 keys product key and product url.
use std::collections::hash_map::Entry::Vacant;
pub struct Products<DB>
where
DB: DatabaseProvider,
{
database: DB,
products: HashMap<String, Product>,
}
pub struct Product {
pub product_id: String,
pub created: String,
pub product_description: String,
pub product_url: String,
}
pub async fn get_product_store_hashmap(&mut self) -> Result<()>
{
// calling the api here, once response is received, store in hashmap
let product = Product {
product_id: somedata,
created: somedata,
product_description: somedata,
product_url:somedata,
};
self.products.insert(product_id.clone(), product);
}
pub async fn insertProduct(&mut self, product:Product) -> Result<()> {
// How to check two keys are contains value.
if let Vacant(entry:Vacant::entry<(string,Product)) = self.product.entry(product_id) {
// insert the data
} else {
// retun no product id found
}
}
Solution 1:[1]
You can use map.contains_key to test.
Example:
fn insertProduct(map: &mut HashMap<String, Product>, product: Product) -> Result<()> {
if map.contains_key(product.product_id) || map.contains_key(product.product_url) {
Err()
} else {
map.insert(product.product_id, Product);
Ok(())
}
}
Solution 2:[2]
You can use Vacant and Occupied to check if key already exists or not and return result according using match
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
use std::io::ErrorKind;
fn main() {
let mut h: HashMap<&str, u8> = HashMap::new();
let value: &str = "a";
// h.entry(value).or_insert(1); // <- uncomment to get err result
let result = match h.entry(value) {
Vacant(entry) => {
entry.insert(1);
Ok(())
},
Occupied(_) => Err(ErrorKind::AlreadyExists)
};
println!("{:?}", result);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Carson |
| Solution 2 | Chandan |
