Pre-RFC, Assign to borrowed mut, - consider dropped


#1

I have found a situation that the borrow checker doesn’t like, but that is guaranteed completely safe, and could possibly be added as an exception to the borrow checker.

While I was able to work around it for my particular case, it did involve a lot more get_mut calls on a HashMap than were needed.

It’s probably easier to show code:

use std::collections::HashMap;

fn main(){
    let mut hmap:HashMap<String,String> = HashMap::new();
    hmap.insert("Hello".to_string(),"Hola".to_string());
    hmap.insert("Goodbye".to_string(),"Adios".to_string());
    {
        let m = hmap.get_mut("Hello").unwrap();
        

        *m = "Salut".to_string();

        //As long as RHS doesn't include require knowledge of 'm'
        //this action is completely safe.
        //m is borrowed so doesn't need to call drop.
        m = hmap.get_mut("Goodbye").unwrap();
        *m = "Au reviour".to_string();
    }
    print!("{:?}\n",hmap);
}

This function doesn’t pass the borrow checker, but I believe it should.

When assigning to an already borrowed variable, as long as the Right Hand Side does not refer to it, it ought to be considered dropped.

While this case is trivial to solve, by adding scopes. Inside of a loop on another range, this is much harder to work around.

statement

When assigning to a borrowed mut variable, as long as that variable is not in the RHS Expression, it can be considered dropped, and its owner can be used in the assignment.

Any thoughts.


#2

This code already compiles on nightly with NLL enabled: https://play.rust-lang.org/?gist=f3ac5a92cf604f2b1717f731817ca140&version=nightly&mode=debug&edition=2015

Here’s the NLL tracking issue. Stabilizing NLL is part of the plan for the Rust 2018 edition.


#3

oh that’s good to know. Thanks.

I’ve stayed away from nightly so far, I guess I’d better check it out.