0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
cm007
  • 1,352
  • 4
  • 20
  • 40
  • I believe your question is already answered by the answers in [How to lookup from and insert into a HashMap efficiently?](https://stackoverflow.com/q/28512394/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as answered. – Shepmaster May 05 '18 at 17:41
  • The [duplicate applied to your question](https://play.rust-lang.org/?gist=7569394ee36b58216d2e3d0c535ece82&version=stable&mode=debug). – Shepmaster May 05 '18 at 17:43

0 Answers0