How to end a borrow?


#1

Hi again,

a question about borrowing. Let’s say I have the following:

use std::sync::{Arc, Mutex};
use std::collections::HashMap;

fn main() {
    let arc = Arc::new(Mutex::new(HashMap::new()));
    let mut c = C { arc: arc };
    c.insert_some();
}

struct C {
    arc: Arc<Mutex<HashMap<String, i32>>>
}

impl C {
    fn insert_some(&mut self) {
        let mut map = self.arc.lock().unwrap();
        map.insert(String::from("a"), 1);
        map.insert(String::from("b"), 2);
        //drop(map);
        //self.mutate_further();
    }

    fn mutate_further(&mut self) {
    }
}

Now if I uncomment the call to self.mutate_further() I get a borrowing error, as expected.
However, I expected that if I also put in the drop(map) call, the compiler will figure out that the borrow is ended there. Why isn’t that the case?


#2

Borrowing is entirely lexical, currently. Calling drop does not release the borrow. You must use {} for now to create a new scope.

Or, you may want to use the Entry API…


#3

Thanks, I suspected as much.


#4

I wrote a post Strategies for solving ‘cannot move out of’ borrowing errors in Rust about this very issue. In a nutshell, you can create a new scope with curly braces, use a anonymous function or create another function.