HashMap key can't be float number type? why?


#1

this is my code:

use std::collections::HashMap;

pub fn main() {
    let mut a = HashMap::new();
    a.insert(1.0, 1.0);
    a.insert(2.0 2.0);
    
}

the error is:

the trait bound `{float}: std::cmp::Eq` is not satisfied

the trait bound `{float}: std::hash::Hash` is not satisfied

Why f64 type can’t satisfy std::cmp::Eq and hash::Hash?


#2

f64 doesn’t implement Eq because NaN is not equal to itself, so it would be impossible to retrieve a HashMap entry with NaN as the key.

The ordered-float crate (docs) has wrapper types that you can use to store floats in a HashMap, either by asserting they are not NaN, or by changing the way NaN is sorted and compared.


#3

Also, there’s a good chance that it won’t do what you want anyways. If you do any calculations with the floats, rounding errors could prevent you from being able to look up values. Like if you store a value with key 1.0 and retrieve it with key (1.0 / 49.0) * 49, it won’t be present.

Better to use an ordered map, so you can search for keys near the value you’re interested in instead of only finding ones that are exactly equal.


#4

thanks


#5

thank you