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


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();
        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();

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.


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.



This code already compiles on nightly with NLL enabled:

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



oh that’s good to know. Thanks.

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


closed #4

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.