title: How can I use a HashMap with f64 as key in Rust?
body: <p>I want to use a <code>HashMap&lt;f64, f64&gt;</code>, for saving the distances of a point with known x and key y to another point. <code>f64</code> as value shouldn't matter here, the focus should be on key.</p>
  
  <pre><code>let mut map = HashMap&lt;f64, f64&gt;::new();
  map.insert(0.4, f64::hypot(4.2, 50.0));
  map.insert(1.8, f64::hypot(2.6, 50.0));
  ...
  let a = map.get(&amp;0.4).unwrap();
  </code></pre>
  
  <p>As <code>f64</code> is neither <code>Eq</code> nor <code>Hash</code>, but only <code>PartialEq</code>, <code>f64</code> is not sufficient as a key. I need to save the distances first, but also access the distances later by y. The type of y needs to be floating point precision, but if doesn't work with <code>f64</code>, I'll use an <code>i64</code> with an known exponent.</p>
  
  <p>I tried some hacks by using my own <code>struct Dimension(f64)</code> and then implementing <code>Hash</code> by converting the float into a <code>String</code> and then hashing it.</p>
  
  <pre><code>#[derive(PartialEq, Eq)]
  struct DimensionKey(f64);
  
  impl Hash for DimensionKey {
      fn hash&lt;H: Hasher&gt;(&amp;self, state: &amp;mut H) {
          format!("{}", self.0).hash(state);
      }
  }
  </code></pre>
  
  <p>It seems very bad and both solutions, my own struct or float as integers with base and exponent seem to be pretty complicated for just a key.</p>
  
  <p>Update:
  I can guarantee that my key never will be <code>NaN</code>, or an infinite value. Also, I won't calculate my keys, only iterating over them and using them. So there should no error with the known error with <code>0.1 + 0.2 ≠ 0.3</code>.
  <a href="https://stackoverflow.com/questions/28247990/how-to-do-a-binary-search-on-a-vec-of-floats">How to do a binary search on a Vec of floats?</a> and this question have in common to implement total ordering and equality for a floating number, the difference lies only in the hashing or iterating.</p>