Return do not release mutable borrow

From the following code: Rust Playground

It seems that the borrow checker keeps the i variable mutably borrowed after the return. Why? I do not use it after?

How to fix the issue to make the code works?

This is a known limitation of the current borrow checker, which will be fixed in the next-generation borrow checker Polonius. For now, working around the problem in safe Rust might require something like this, which unfortunately means looking up the key twice every time:

    fn get_mut(&mut self, key: &i32) -> Option<&mut String> {
        if !self.items.contains_key(key) {
            self.cache();
        }
        self.items.get_mut(key)
    }

In some cases you might be able to rewrite this to be more efficient using HashMap::entry. In others, an optimal workaround might require unsafe code, until Polonius is finished.

5 Likes

Depending on what cache does, it looks like it's good to use .entry(*key) instead of get_mut in this case, and you might be able to avoid a second lookup that way.

1 Like