How to insert into a hash map a key value pair if and only if the key is not already in the map?

⚓ Rust    📅 2025-10-09    👤 surdeus    👁️ 5      

surdeus

I have this method:

    pub fn AddCab(&mut self,name: String,color: String) -> &Cab {               
        match self.cabs.get(&name) {                                            
            None => {                                                           
                self.cabs.insert(name,Cab::new(name.clone(),color));            
                &self.cabs[&name]                                               
            },                                                                  
            Some(c) => c,                                                       
        }                                                                       
    }                                                                           

And I am getting this error:

error[E0502]: cannot borrow `self.cabs` as mutable because it is also borrowed a
s immutable
   --> src/lib.rs:699:17
    |
696 |       pub fn AddCab(&mut self,name: String,color: String) -> &Cab {
    |                     - let's call the lifetime of this reference `'1`
697 |           match self.cabs.get(&name) {
    |           -     --------- immutable borrow occurs here
    |  _________|
    | |
698 | |             None => {
699 | |                 self.cabs.insert(name,Cab::new(name.clone(),color));
    | |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ muta
ble borrow occurs here
700 | |                 &self.cabs[&name]
701 | |             },
702 | |             Some(c) => c,
703 | |         }
    | |_________- returning this value requires that `self.cabs` is borrowed for
 `'1`

The cabs field is declared as: cabs: CabNameMap.

Is there a way around this?

4 posts - 3 participants

Read full topic

🏷️ Rust_feed