I'm super new to Rust. My code looks kind of similar to below piece of code and it is giving me compilation error.
#![allow(dead_code)]
#![allow(unused_variables)]
use std::collections::HashMap;
struct Usermap {
map: HashMap<i32,String>
}
struct UserDb {
pub db: Option<Usermap>
}
fn main() {
let mut umap: Usermap = Usermap { map: HashMap::new() };
umap.map.insert(10, String::from("usr1"));
umap.map.insert(13, String::from("usr2"));
umap.map.insert(30, String::from("usr3"));
let mut usrdb: UserDb = UserDb { db: Some(umap) };
let which_usr = String::from("usr1");
remove_usr(&mut usrdb, &which_usr);
}
fn remove_usr(usr: &mut UserDb, which_usr: &String) {
if let Some(db) = &mut usr.db {
for (key, value) in &mut db.map {
if value == which_usr {
println!("key matched , removing user..{}", key);
db.map.remove(key); // this line of code is giving me compilation error -
// "cannot borrow `db.map` as mutable more than once at a time"
}
}
}
}
My goal here is to delete a Map element if its "value" matches with "which_usr". What could be the possible solution here?