Borrowing/map from RefCell

Am I wrong to expect this to work ?
Currently it does panic with 'already borrowed: BorrowMutError' but I was hoping it would infer that closure is not FnMut.

let x: RefCell<HashMap<String, String>> = ...

if let Some(v) = x.borrow().get("foo").map(String::to_owned) {
 x. borrow_mut().remove("bar");

if let let's temporary values live for the whole duration of its body, including the guard object from the call to borrow. If you don't need v at all, you can use an ordinary if which behaves differently in this regard. (Together with HashMap::contains_key, or using is_some on the Option)

If you do use v, since you make it owned anyway, you can use a separate let assignment before the if let

let value = x.borrow().get("foo").map(String::to_owned);
// the guard from `borrow` gets dropped
// here, after the `let` statement above
if let Some(v) = value {
  .... // can use `x.borrow_mut` here

Yes, that is what I did at the end, I was just curious why it doesn't work.
Thanks for asnwering.

It's just an annoyance the language has. No one has viable change without breaking things.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.