Remove found entry from HashMap without cloning the key

Viewed 64

I am finding a certain entry in a HashMap (in this case it's the one that's "least used"). I now want to remove that entry from the map. Since the key was obtained from the HashMap itself (and thus is a reference), how can I now use it to remove the entry without cloning the key.

Here is a small, runnable example:

use std::collections::HashMap;

fn main() {
    let mut usage = HashMap::<String, usize>::new();
    
    usage.insert("entry one".to_owned(), 5);
    usage.insert("entry two".to_owned(), 1);
    
    let mut least_used: Option<(&String, &usize)> = None;
    for curr in usage.iter() {
        if let Some(prev) = least_used {
            if curr.1 < prev.1 {
                least_used = Some(curr);
            }
        } else {
            least_used = Some(curr);
        }
    }
    
    println!("{:?}", least_used);
    
    usage.remove(least_used.unwrap().0);
}

Rust playground

The error I'm getting is:

cannot borrow `usage` as mutable because it is also borrowed as immutable
0 Answers
Related