Calling a `&mut` object's method in a loop - Mutable borrow starts here in previous iteration of loop

You're right about that. I totally forgot about the loop when I wrote what I did. It'd still error at the second iteration, but at runtime. It'd complain about the RefCell already having handed out a Ref<...> when it tries to get a MutRef<...> for manipulating the HashMap.

In that case, these are all the options I could think of, that'd work:

  • Implement your own hash map with a fixed capacity, that can add new keys without requiring a mutable reference; Foo::get doesn't require &mut self in that case, anymore (not recommended)
  • Instead of storing a reference to the result in the Vec, only store the key in the Vec and let the program lookup the result dynamically whenever needed; you're cashing the result, i.e. calling Foo::get multiple times may be acceptable (recommended, if cloning the result is not an option)
  • Do it like suggested above: Clone the result (recommended, if cloning is acceptable; for Copy types, it's always fine to clone them)
2 Likes