I am trying to invert a collection of key-value pairs. For example,
a: 1, 2, 3
b: 3, 4, 5
to
1: a
2: a
3: a, b
4: b
5: b
I have the following Rust code:
use std::collections::{HashMap, HashSet};
pub fn convert_map(my_tuples: Vec<(String, Vec<String>)>) -> HashMap<String, HashSet<String>> {
let mut my_map = HashMap::<String, HashSet<String>>::new();
for my_tuple in my_tuples {
for new_key in my_tuple.1 {
match my_map.get(&new_key) {
Some(val) => {
val.insert(my_tuple.0);
}
None => {
let mut new_val = HashSet::new();
new_val.insert(my_tuple.0);
my_map.insert(new_key, new_val);
}
}
}
}
my_map
}
However, I am getting the following compiler errors:
error[E0596]: cannot borrow immutable borrowed content `*val` as mutable
--> src/main.rs:9:21
|
9 | val.insert(my_tuple.0);
| ^^^ cannot borrow as mutable
error[E0382]: use of moved value: `my_tuple.0`
--> src/main.rs:9:32
|
9 | val.insert(my_tuple.0);
| ^^^^^^^^^^ value moved here in previous iteration of loop
|
= note: move occurs because `my_tuple.0` has type `std::string::String`, which does not implement the `Copy` trait
error[E0382]: use of moved value: `my_tuple.0`
--> src/main.rs:13:36
|
9 | val.insert(my_tuple.0);
| ---------- value moved here
...
13 | new_val.insert(my_tuple.0);
| ^^^^^^^^^^ value used here after move
|
= note: move occurs because `my_tuple.0` has type `std::string::String`, which does not implement the `Copy` trait
error[E0502]: cannot borrow `my_map` as mutable because it is also borrowed as immutable
--> src/main.rs:14:21
|
7 | match my_map.get(&new_key) {
| ------ immutable borrow occurs here
...
14 | my_map.insert(new_key, new_val);
| ^^^^^^ mutable borrow occurs here
15 | }
16 | }
| - immutable borrow ends here
I am new to Rust and am not sure how to correctly state the mutability so that this will compile.