0

I have a variable called address_mapping that is part of a public struct. I've put all of the code in the same function, and I'm running into some issues with referencing.

match self.address_mapping.get(&tx_outpoint) {
    Some(address_info) => {                          
        balances.push(address_info.clone().current_balance as f64);
        address_info_vec.push(address_info);
        tx_outpoint_vec.push(tx_outpoint);
    }
};
...
self.address_mapping.remove(&tx_outpoint);

match self.address_mapping.get(&tx_outpoint) { | -------------------- immutable borrow occurs here

self.address_mapping.remove(&tx_outpoint); | ^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

It happens again in another section of the code, even if I use {} to set the scope. I also tried using the drop method on _borrow. Also, I think it's a bad idea to use the clone method because this data structure can get quite big.

{
     let _borrow = &mut self.address_mapping;
     for (tx_outpoint, address_info) in _borrow {
         txoutpoint_to_delete.push(tx_outpoint);
     }
}
...
for tx_outpoint in &txoutpoint_to_delete { self.address_mapping.remove(tx_outpoint); }
Alessandro
  • 4,000
  • 12
  • 63
  • 131
  • Please provide a [MCVE]. We cannot compile your code to see the underlying error. Also, please take the time to look at the styling of your post — your error messages are completely unreadable when formatted as a quote. – Shepmaster Feb 04 '18 at 18:43
  • Additionally, you are getting a reference to the insides of your `HashMap` (`address_info`) and storing that in a `Vec` (`address_info_vec`). This means that when you call `address_mapping.remove`, you may potentially invalidate all of the references into the `HashMap`; using them would incur memory unsafety. This is **exactly** the kind of bug that Rust prevents. – Shepmaster Feb 04 '18 at 18:50

0 Answers0