title: How to implement Eq and Hash for my own structs to use them as a HashMap key?
body: <p>I have two structs, <code>A</code> and <code>B</code>, and I want to use a <code>HashMap&lt;A, B&gt;</code>. I have a piece of code like this:</p>
  <pre><code>use std::collections::HashMap;
  
  pub struct A {
      x: i32,
      y: i32,
      title: String,
  }
  
  pub struct B {
      a: u32,
      b: u32,
  }
  
  fn main() {
      let map = HashMap::new();
      map.insert(
          A {
              x: 10,
              y: 20,
              title: &quot;test&quot;.to_string(),
          },
          B { a: 1, b: 2 },
      );
  }
  </code></pre>
  <p>But the compiler gives me these errors:</p>
  <pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `A: std::cmp::Eq` is not satisfied
    --&gt; src/main.rs:16:9
     |
  16 |     map.insert(
     |         ^^^^^^ the trait `std::cmp::Eq` is not implemented for `A`
  
  error[E0277]: the trait bound `A: std::hash::Hash` is not satisfied
    --&gt; src/main.rs:16:9
     |
  16 |     map.insert(
     |         ^^^^^^ the trait `std::hash::Hash` is not implemented for `A`
  </code></pre>
  <p>I know that I must implement these traits, but after hours of searching  the web, I have found nothing about implementing them.</p>
  <p>My actual code is more complicated, and my structs contain other structs (I've edited the code).</p>
  <p>I've implemented the <code>Hash</code> trait:</p>
  <pre><code>impl std::hash::Hash for A {
      fn hash&lt;H&gt;(&amp;self, state: &amp;mut H)
      where
          H: std::hash::Hasher,
      {
          state.write_i32(self.x);
          state.finish();
      }
  }
  </code></pre>
  <p>I made an implementation for <code>PartialEq</code> also:</p>
  <pre><code>impl PartialEq for A {
      fn eq(&amp;self, other: &amp;A) -&gt; bool {
          self.x == other.x
      }
  }
  </code></pre>
  <p>But the compiler continues to complain, this time about <code>Eq</code>:</p>
  <pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `A: std::cmp::Eq` is not satisfied
    --&gt; src/main.rs:16:9
     |
  16 |     map.insert(
     |         ^^^^^^ the trait `std::cmp::Eq` is not implemented for `A`
  </code></pre>
  <p>How can I implement <code>Eq</code>? Why is there no implementation in the docs?</p>