title: Updating mutable HashMap in a while loop
body: <p>I am trying to implement Karger's algorithm in Rust and I have run into an issue while trying to update a mutable hashmap in a while loop.</p>
  
  <p>The map is updated successfully, but then in the next iteration when it was cloned, the values that were updated don't seem to have been changed. However removing elements from the map is reflected on later iterations.</p>
  
  <p>I have tried debugging and printing the values of the map, but the sequence of events doesn't make sense to me.</p>
  
  <pre><code>use itertools::Itertools;  // 0.8.0
  use rand::seq::{IteratorRandom, SliceRandom}; // 0.6.5
  use std::collections::HashMap;
  
  fn contract_edge(graph: &amp;mut HashMap&lt;i32, Vec&lt;i32&gt;&gt;, num_trials: i32) {
      let mut count = 0;
  
      while graph.len() &gt; 2 &amp;&amp; count &lt; num_trials {
          // clone graph so I can mutate graph later
          let imut_graph = graph.clone();
  
          // choose random node
          let from_value = imut_graph
              .keys()
              .choose(&amp;mut rand::thread_rng())
              .unwrap()
              .clone();
          let values = imut_graph.get(&amp;from_value);
          let to_value = values
              .unwrap()
              .choose(&amp;mut rand::thread_rng())
              .unwrap()
              .clone();
  
          let from_edges = imut_graph[&amp;from_value].iter().clone();
  
          // accessing to_value in imut_graph gives error here later
          let to_edges = imut_graph[&amp;to_value]
              .iter()
              .clone()
              .filter(|&amp;x| *x != from_value &amp;&amp; *x != to_value);
  
          let new_edges = from_edges.chain(to_edges);
  
          // since I am mutating the graph I thought the next time is is clone it would be updated?
          graph.insert(from_value, new_edges.map(|v| v.clone()).collect());
          graph.remove(&amp;to_value);
          for (_key, val) in graph.iter_mut() {
              *val = val
                  .iter()
                  .map(|v| if v == &amp;to_value { &amp;from_value } else { v })
                  .unique()
                  .cloned()
                  .collect();
          }
          count += 1;
      }
  }
  </code></pre>
  
  <p>When I try to access the map, I get element not found error, but the keys which have been removed should not exist in the vector values at that point.</p>
  
  <p>I am convinced this is something I don't understand about (Im)mutability in Rust.</p>