0

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?

dnn
  • 127
  • 3
  • 10
  • 1
    What's wrong with just `db.map.remove(id)`, without iteration? – Cerberus Dec 09 '21 at 04:53
  • 1
    Why have the loop and if at all? Just call remove. HashMaps are designed to lookup and modify by the key. You can look at the return value if you're really interested in printing whether it was removed or not. – kmdreko Dec 09 '21 at 04:54
  • My bad! I just edited the question. Here my goal is to remove based "value" not the key – dnn Dec 09 '21 at 07:51

0 Answers0