title: Checking two HashMaps for identical keyset in Rust
body: <p>Suppose I have two HashMaps (or, <em>any</em> map structure that has keys mapping to something else), map1 and map2, and I want to ensure that they have an identical set of keys. Note that the <em>keys</em> are the same type in the maps, but the <em>values</em> are <em>not</em>.</p>
  
  <p>My initial attempt at this was just:</p>
  
  <pre><code>map1.keys().eq(map2.keys())
  </code></pre>
  
  <p>and, although this worked the <em>first</em> time, the <em>eq</em> function for iterators (understandably) seems to compare the keys <em>in the order produced by the iterator, not by checking for the existence of a key anywhere in the second iterator</em>. This, combined with the fact that HashMap::keys() produces an iterator where the <em>order of the keys is non-deterministic</em> means that the equality function will often fail even if the sets (in the set-theory sense) of the keys are identical.</p>
  
  <p>So, my next attempt was to make a function which did this:</p>
  
  <pre><code>fn keys_match&lt;T:std::cmp::Eq + std::hash::Hash,U,V&gt;(map1:&amp;HashMap&lt;T,U&gt;, map2:&amp;HashMap&lt;T,V&gt;) -&gt; bool {
    // Make sure that map1.keys() ⊆ map2.keys()
    for key in map1.keys() {
      match map2.get(key) {
        None =&gt; return false,
        Some(_) =&gt; {}
      }
    }
    // If map1.keys() ⊆ map2.keys() and their sizes equal, then the sets are equal
    map1.len() == map2.len()
  }
  </code></pre>
  
  <p>Note for Rust beginners: My first try at this was actually with the knowledge that the keys in the maps were of type String, so my function signature was:</p>
  
  <pre><code>fn keys_match&lt;T,U&gt;(map1:&amp;HashMap&lt;String,T&gt;, map2:&amp;HashMap&lt;String,U&gt;) -&gt; bool
  </code></pre>
  
  <p>until I realized that I could even genericize the <em>common key type</em> by requiring them to have the Eq and Hash traits.</p>
  
  <p><strong>Question: Is there a more-terse way of doing this in Rust?</strong></p>