colinfang
colinfang

Reputation: 21707

Best way to modify hashmap from reference to the value

use std::collections::{HashMap, HashSet};
use std::hash::{Hash};

fn test(data: &mut HashMap<String, HashSet<String>>) {
    match data.get("foo") {
        None => return,
        Some(xs) => {
            let xs: Vec<String> = xs.iter().map(|x| x.to_owned()).collect();
            // How to drop `data` here so that I can borrow `data`.
            for x in xs {
                // Mutable borrow occurs, because previous `data` is still in scope.
                data.remove(&x);
            }
        }
    }
}

The code above doesn't work, as I mutable borrowed data again while the previous borrow is still in scope. However, I couldn't find an easy way to drop the binding of the previous borrowing.

Also, is there any better way to copy the xs so that I can modify the hashmap while iterating it.

Upvotes: 2

Views: 368

Answers (1)

E_net4
E_net4

Reputation: 29972

You were very close to a solution. Once you have an independent vector, you can just move it out of the scope borrowing the map:

use std::collections::{HashMap, HashSet};

fn test(data: &mut HashMap<String, HashSet<String>>) {
    let xs: Vec<String> = match data.get("foo") {
        None => return,
        Some(xs) => {
            xs.iter().map(|x| x.to_owned()).collect()
        }
    };
    for x in xs {
        data.remove(&x);
    }

}

Playground

Upvotes: 2

Related Questions